skip to Main Content

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


  1. 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' );
    
    Login or Signup to reply.
  2. Try out this code:

    You need to do concatenation with $html.

    function home_loop_shortcode() {
        $html = '';
        $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' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search