Home > Software engineering >  Custom WP post loop displays only one post
Custom WP post loop displays only one post

Time:11-15

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 >
    <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!

  • Related