I made a shortcode in order to display the loop on my custom homepage :
function home_loop_shortcode() {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => '8',
'cat' => '3, 6',
'orderby' => 'date'
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$postlink = get_permalink(get_the_ID());
$html = '<li><a href="' . $postlink . '">' . get_the_title() . '</a></li>';
}
}
return $html;
wp_reset_postdata();
}
add_shortcode( 'loop', 'home_loop_shortcode' );
I actually have 8 posts in category ID 3 and 6, but only the first post is displayed. The code is nested inside this HTML:
<div class="home-loop">
<h3>Latest posts</h3>
<ul>
[loop]
</ul>
</div>
Even if I remove 'cat'
line, or replace it by 'category_name' => 'foo'
, or if I set 'posts_per_page' => -1
, nothing change. I probably miss something obvious… Help!ðŸ˜ðŸ˜…
2
Answers
you are overwriting
$html
with the last post instead of concatenating it.so define
$html = '';
and then concatenate it:Try out this code:
You need to do concatenation with $html.