Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom WP post loop displays only one post

Tags:

wordpress

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

like image 437
dragoweb Avatar asked Jul 18 '26 01:07

dragoweb


1 Answers

you are overwriting $html with the last post instead of concatenating it.

so define $html = ''; and then concatenate it:

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);
    $html = '';
    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' );
like image 176
Moishy Avatar answered Jul 20 '26 11:07

Moishy