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.
- 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.
- Removing wp_reset_postdata() does nothing as much as I can see, doesn't resolve my issue.
- Adding
<br>
or clearfix divs does not resolve the issue. - Having the return inside the while loop only posts the last recent post as it closes the loop once returned.
- 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
- Removed the return
- Instead of incrementing the $text variable, i added an echo for the line.
- Instead of using the_permalink() and the_title(), I used get_the_permalink() and get_the_title().