How can I improve the performance of this query_posts loop?

I created a WordPress page template to build a customised XML feed for certain WordPress posts on my site. Specifically, the page template renders XML and only includes certain custom post types and only if these posts contain specific meta data.

I'm using the data to feed WordPress content to an iOS application. It seems to work great; however, the response times from the server vary and often fail. My hosting company ( MediaTemple ) has suggested I could improve performance by making the database query more efficient.

Are there any standard optimisation tips for this kind of query?

?php
$numposts = -1;
$posts = query_posts( 'showposts=' . $numposts . 'post_type=listings' );
header("Content-Type: application/rss+xml; charset=UTF-8");
echo '?xml version="1.0"?';
?
rss version="2.0"
channel
    titleMy custom feed/title
    ?php foreach ($posts as $post) { if ( get_post_meta($post-ID, 'mymeta', true) ) { ?
        item
            various item elements...
        /item
    ?php } ?
    /channel
/rss

Topic ios loop query-posts database Wordpress optimization

Category Web


Not sure how dramatic this'll be, but it should improve nontheless:

<?php

/**
 * You can try forcibly splitting the query (grabbing IDs *then* all fields)
 * Works well for large post results. (available WP 3.4+)
 */ 
add_filter( 'split_the_query', '__return_true' );

$posts = get_posts( array(  
    'post_type' => 'listings',
    'posts_per_page' => -1,

    /* Disable term caching ONLY if you're not using them in your loop. */
    'update_post_term_cache' => false,

    /* Ensures SQL_CALC_FOUND_ROWS is disabled */
    'no_found_rows' => true,

    /* If you're only operating on these, filter out at the query stage rather than the loop. */
    'meta_key' => 'mymeta',
));

header( 'Content-Type: application/rss+xml; charset=UTF-8' );
echo '<?xml version="1.0"?>';

?>
<rss version="2.0">
<channel>
    <title>My custom feed</title>
        <?php foreach ( $posts as $post ) :  ?>
            <item>
                <various item elements...>
            </item>
        <?php endforeach ?>
    </channel>
</rss>

you can hook up Transient API for this and store the results of the wp_query in your database for 1 - 2 hours ...

in the WordPress Plugin book from Wrox there is a great example of this kind of query or try looking at Justin Tadlock's website

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.