Search code examples
wordpressshortcode

Shortcode showing single post only


I am creating a testimonial plugin. I registered a shortcode querying the custom testimonial posts but the shortcode loads only one posts where I need to load 10 posts. So where is the problem that the shortcode doesn't load all custom posts?

The codes are here:

function testimonial_text_shortcode(){
    global $post;
    $q = new WP_Query(
        array('posts_per_page' => 10, 'post_type' => 'rwpt_custom_post')
        );      
    while($q->have_posts()) : $q->the_post();
        $list = '<li><p>'.get_the_content().'</p></li>';        
    endwhile;
    wp_reset_query();
    return $list;
}

add_shortcode('test_text', 'testimonial_text_shortcode');

Solution

  • You're overriding the value of $list in each loop iteration so in the end it will only hold the last value.

    Modify your code to append to the variable instead:

    function testimonial_text_shortcode(){
        global $post;
        $q = new WP_Query(
            array('posts_per_page' => 10, 'post_type' => 'rwpt_custom_post')
            );
        $list = '<ul>';
        while($q->have_posts()) : $q->the_post();
            $list .= '<li><p>'.get_the_content().'</p></li>';        
        endwhile;
        $list .= '</ul>';
        wp_reset_query();
        return $list;
    }
    
    add_shortcode('test_text', 'testimonial_text_shortcode');