0
votes

So basically I'm creating a small function to get the most recent posts with a certain category from WordPress, and just link them in a Test page. The function itself works, grabbed it from this stackexchange thread. My while loop set up currently ignores all the HTML/CSS i try to return.

  1. Removing the_post() ignores $args and lists all the posts from all the categories instead of just the one i listed, but still ignores the HTML.
  2. Removing wp_reset_postdata() does nothing as much as I can see, doesn't resolve my issue.
  3. Adding <br> or clearfix divs does not resolve the issue.
  4. Having the return inside the while loop only posts the last recent post as it closes the loop once returned.
  5. Tried using echo instead of return, same result.
function link_recent_posts(){
    $text = "";
    $args = array('posts_per_page' => 2, 
                  'cat' => '144',);
    $q = new WP_Query($args);
    if($q->have_posts() ){
        while( $q->have_posts() ){
            $q->the_post();
            $text .= "<a href='".the_permalink()."'>".the_title()."</a><br>";
        }
        wp_reset_postdata();
    }
    return $text;
}
add_shortcode('TestRecentPosts', 'link_recent_posts');

The expected result should be

<a href='LINK1'> TITLE TITLE TITLE </a><br>
<a href='LINK2'> TITLE TITLE TITLE </a><br>

The result I get is :

<div class="wordpress-content-section">
    <div class="clearfix"></div>
    LINK 1
    TITLE 1
    LINK 2
    TITLE 2
    <a href=""></a><br>
    <a href=""></a><br>
</div>

Imagine that there's 0 spaces between the links and titles.

Issue Resolved

  1. Removed the return
  2. Instead of incrementing the $text variable, i added an echo for the line.
  3. Instead of using the_permalink() and the_title(), I used get_the_permalink() and get_the_title().
1
try using echo instead of returnTibs
Same result as question.Adrien J.
remove the return $text; line instead of appending the HTML inside the $text variable, echo it directly do echo "<a href='".the_permalink()."'>".the_title()."</a><br>";Tibs
and also, try using get_the_permalink(); and get_the_title();Tibs
What it does is place the anchor tags and br right after the_permalink, and the_title. Better than nothing, but stuff doesn't go in the right place still. edit: get_the_permalink() and get_the_title() resolved it. thanks!Adrien J.

1 Answers

0
votes

Use get_the_permalink() and get_the_title() instead. the_permalink() and the_title() echoes the results directly.

SEE

https://core.trac.wordpress.org/browser/tags/5.1.1/src/wp-includes/post-template.php#L0

https://developer.wordpress.org/reference/functions/the_permalink/