0

I have a custom loop that is displaying a "most popular" posts section. It first creates a linked container (<a href="<?php the_permalink(); ?>"> ... </a>), and then stores data from the current post in the loop within that container.

If the post has a thumbnail, it displays the image (if ( has_post_thumbnail() ) { the_post_thumbnail(); }). Otherwise, it executes the_content(); in the else { } part, wherein it can grab an iframe and display that instead.

For some reason, if it goes into the else { } part, it will close the opening <a href="<?php the_permalink(); ?>"> statement with a closing </a> tag first. This results in <div class="most-popular-article"></div> and its contents coming after the <a></a> container rather than inside of it.

Does anyone know what exactly is happening here, or how to prevent it from happening?

        <a href="<?php the_permalink(); ?>">
            <div class="most-popular-article">
                <?php if ( has_post_thumbnail() ) {
                the_post_thumbnail();
                }
                else {
                the_content();
                } ?>
                <h3><?php the_title(); ?></h3>
            </div>
        </a>
  • Does the posts content have links in it? You can’t have links inside links. – Jacob Peattie Dec 8 '17 at 1:41
  • The post is not composed with any links in it, but it renders with the permalink in the <div class="most-popular-article"></div>, which I'm guessing gets pulled out from the_content(); – coffeebot Dec 8 '17 at 1:45
  • There's most likely a problem with the iframe part. You shouldn't render an iframe inside an anchor. Try putting some normal text as content, and see if the problem persists. – Jack Johansson Dec 8 '17 at 7:20
1

the_content() is probably rendering a link ( or maybe your browser may be auto formatting one ).

You can test if this is so by instead of using the_content();

using

// Get the Content of the post 
$postContent = get_the_content();
// Escape all the HTML
$postContent =  htmlentities($postContent);
// Print it to screen and verify if any links are inside.
print_r($postContent);

if you have links in the content or expect them try simply replacing them like

// Get the Content of the post 
$postContent = get_the_content();
// some simple regex 
$postContent = preg_replace('/<a.+?>/','<strike>',$postContent);
// some more simple regex 
$postContent = preg_replace('/<\/a>/','</strike>',$postContent);
echo $postContent;

The above code will render all the links as strike through text you could replace this with underlines or even with a span that with the clever use of capture groups could be used to bind click events to said spans and you could still have functional links.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.