• I need to show a lot of information in the sidebars and footers of my wordpress installation. It seems that each new wp_query adds at least 5 database calls, which seems a lot. Is it really the most efficient way of querying additional posts (outside of the main loop), or is there a better way?

    Can someone validate that this is the way it should be done?

    Here is an example, which seems to add 5 database queries:

    <?php $my532_query = new WP_Query('category_name=CATNAME&showposts=5'); ?>
    <?php while ($my532_query->have_posts()) : $my532_query->the_post(); ?>
    <?php the_title(); ?>
    <?php the_excerpt(); ?>
    <?php endwhile; ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • Using get_posts() instead of making a new WP_Query might be lighter.

    http://codex.wordpress.org/Template_Tags/get_posts

    For example:

    global $post;
    $tmp_post = $post;
    $args = array (
        'numberposts' => 5,
        'category' => 7
    );
    
    $my_posts = get_posts( $args );
    foreach( $myposts as $post ) { setup_postdata( $post );
        /* Your display stuff */
    }
    $post = $tmp_post;

    Using get_posts() instead of making a new WP_Query might be lighter

    Not sure if there would be much difference, as it is just a Wrapper with defaults $args for WP_Query.

    get_posts() makes use of the WP_Query class to fetch posts.
    See the parameters section of the WP_Query documentation for a list of parameters that this function accepts.

    Only thing I would add would be like Big Bagle to store the WP_Query and set it to NULL before the new query, and use a template part like content-custom.php adding the output in this file.

    SAMPLE UNTESTED

    <?php
    $tmp_query = $wp_query;
    $catid = '123';
    $do_not_show_stickies = 1; // 0 to show stickies
    $args = array(
    	'cat' => $catid,						'paged' => $paged,
    	'ignore_sticky_posts' => $do_not_show_stickies
    );
    $wp_query= null;
    $wp_query = new WP_Query();
    $wp_query->query( $args );
    ?>
    
    <?php if ( $wp_query->have_posts() ) :
       while ( $wp_query->have_posts() ) :
          $wp_query->the_post();
          get_template_part( 'content', 'custom' );
       endwhile;
    endif; 
    
    $wp_query = $tmp_query;
    ?>

    To save the query reads it is more important to have a good cache plugin to serve html temporary pages limiting the queries.

    HTH

    David

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘New wp_query the most efficient way concerning database calls?’ is closed to new replies.