• Resolved imaginocracy

    (@imaginocracy)


    I am trying to set up a shortcode for a slider using the Bootstrap 3 framework.

    I’ve nearly got it working properly, but I am perplexed as to why the HTML is outputting only a single post, instead of the 3 posts I have in that category.

    /**
     * Add Flavor Slider Shortcode
     */
    
    function register_shortcodes(){
    	add_shortcode('flavor-slider', 'client_flavors_slider_function');
    }
    
    add_action('init', 'register_shortcodes');
    
    function client_flavors_slider_function() {
    	extract(shortcode_atts(array(
    		'posts' => 3,
    		), $atts));
    
    	$flavor_query = new WP_query('category_name=flavor');
    
    	if ($flavor_query -> have_posts()) : while ($flavor_query -> have_posts()) : $flavor_query -> the_post();
    			$return_string = '<div class="item active"><div class="featured-image col-sm-5">'.get_the_post_thumbnail().'</div>
    			<div class="post-content col-sm-5 col-sm-offset-2"><h2>'.get_the_title().'</h2><p>'.get_the_content().'</p></div></div>';
    		endwhile;
    	endif;
    
    	return $return_string;
    }
    
    add_shortcode('flavor-slider', 'client_flavors_slider_function');

    The doozy is that if I remove post #1 and refresh the page, it then pulls post #2 from that category. So it recognizes the posts and the category but is only creating markup for one post. Trying to get 3 posts to show.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You should define $return_string outside the while loop. Inside the while loop, you should append data to $return_string.

    Here, I’ve changed your function a little:

    function client_flavors_slider_function($atts)
    {
    	extract(
    		shortcode_atts(
    			array(
    				'posts' => 3,
    			),
    			$atts,
    			'flavor-slider'
    		)
    	);
    
    	$flavor_query = new WP_Query(
    		array(
    			'category_name'  => 'audio',
    			'posts_per_page' => $posts,
    		)
    	);
    
    	$flavor_output = false;
    
    	if ($flavor_query->have_posts())
    	{
    		while ($flavor_query->have_posts())
    		{
    			$flavor_query->the_post();
    
    			$flavor_output .= '<div class="item active">';
    			$flavor_output .= '<div class="featured-image col-sm-5">'.get_the_post_thumbnail().'</div>';
    			$flavor_output .= '<div class="post-content col-sm-5 col-sm-offset-2">';
    			$flavor_output .= '<h2>'.get_the_title().'</h2>';
    			$flavor_output .= '<p>'.get_the_content().'</p>';
    			$flavor_output .= '</div>';
    			$flavor_output .= '</div>';
    		}
    	}
    
    	return $flavor_output;
    }
    Thread Starter imaginocracy

    (@imaginocracy)

    That worked, thank you!

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘WP Query in functions.php returning only one entry’ is closed to new replies.