0

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)?

3
  • 1
    Shortcodes must return their content, not directly print or echo. Read the codex page for add_hortcodes.
    – Milo
    Jan 5 '14 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. Jan 5 '14 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 '14 at 18:12
0

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');
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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