Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I created a function (in function.php) that allows me to put additional loops for different categories into pages:

function custom_summary($atts) {
    extract(shortcode_atts(array(  
        "category" => "",
        "posts" => ""
    ), $atts));

    $my_query = new WP_Query("category_name=$category&posts_per_page=$posts");
    while ($my_query->have_posts()) : $my_query->the_post();
        // Do all the things.
    endwhile;

}
add_shortcode('summary', 'custom_summary');

Unfortunately, no matter where I put the shortcode [summary category="cats" posts="3"] it is always displayed before the content of the page. In other words, the new WP_Query is processed before anything else happens with page's contents. How can I make the loop appear exactly where I put the shortcode in the backend (e.g. between content on the page)?

share|improve this question
1  
Shortcodes must return their content, not directly print or echo. Read the codex page for add_hortcodes. –  Milo Jan 5 at 16:19
    
@Milo, I think you have a very good point there: "Any string returned (not echoed) by the shortcode handler will be inserted into the post body in place of the shortcode itself." I will try this and update. –  Christian Macht Jan 5 at 16:26
    
also don't forget to use wp_reset_postdata after running secondary loops, so any template functions will give you the correct data from the original loop. –  Milo Jan 5 at 18:12

1 Answer 1

up vote 0 down vote accepted

Use buffer to simply do that with ob_start() & ob_get_clean().

function custom_summary($atts) {
    extract(shortcode_atts(array(  
        "category" => "",
        "posts" => ""
    ), $atts));

    ob_start();

    $my_query = new WP_Query("category_name=$category&posts_per_page=$posts");
    while ($my_query->have_posts()) : $my_query->the_post();
        // Do all the things.
    endwhile;

    wp_reset_postdata();

    return ob_get_clean();

}
add_shortcode('summary', 'custom_summary');
share|improve this answer
    
Thanks, that's exactlly what I did! Well explained in the Shortcode API Codex Page as well. –  Christian Macht Jan 5 at 21:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.