I'm using query_posts quite a bit on my site as it seems to offer the most flexibility when processing the values of custom WP Types fields.
I was wondering if there was any way to make my code more efficient? In the example below I'm using query_posts to pull a list of all posts with a post type of "press" and then sorting them into lists by year of publication date. It feels quite resource-heavy though as the page load time is on the long side.
<section id="press-archive">
<ul>
<?php
query_posts('posts_per_page=-1&post_type=press&order=desc&orderby=meta_value_num&meta_key=wpcf-publication-date');
$current_year = '';
while ( have_posts() ) : the_post();
global $post;
$this_year = get_post_meta( $post->ID, 'wpcf-publication-date', true );
$this_year = date('Y', $this_year);
if (($this_year != $current_year)) :
if ($current_year != '')
echo '</ul>' . "\n";
echo '</li>' . "\n";
echo '<li class="year">' . "\n";
echo '<h2 class="header">' . $this_year . '</h2>' . "\n";
echo '<ul>' . "\n";
$current_year = $this_year;
endif;
echo '<li id="' . $this_year . '">' . "\n";
?>
<span class="source"><?php echo(types_render_field("source", array())); ?></a> — <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a> <span class="publication-date">(<?php echo(types_render_field("publication-date", array("format" => "jS F"))); ?>)</span>
</li>
<?php
endwhile;
if ($current_year != '') echo '</li>' . "\n";
wp_reset_postdata();
?>
</ul>
</section>
Any help on making this less resource-heavy would be fantastic. Thank you.
Hi bonnieG,
There is only one query_posts in your code, I don't think it will make the problem resource-heavy, maybe there is some other plugin cause this problem. please try deactivate other plugin and switch your theme to wordpress default theme twentytwelve, and test again.
Regards
Luo
Thanks. I posted the same question on http://wordpress.org/support/topic/alternative-to-query_posts and someone pointed me in the direction of WP_Query which seems much more flexible and suitable for my needs as you can use the Types fields in a lot more ways!
It turns out the performance issue was actually down to running the site on localhost as the live site is working fine.
Thank you!