I'm not sure the appropriate terminology but I have a wordpress "loop" for a custom post type that has roughly 300 results that all get displayed on a single page (no paging). The causes an enormous load on the DB server because for every "post" in the "loop" there are like N database calls (the_title, has_post_thumbnail, get_post_thumbnail_id, the_content, get_post_meta, etc..). What is the wordpress way of optimizing this? For something like this do most developers just drop to doing queries with $wpdb or is the wordpress way to cache the page and move on? I looked at doing straight $wpdb sql queries but grabbing the relevant data (especially images associated with the post) is less then intuitive.

  • Interested in seeing answers but I have never tried to display 300 posts at a time... That is a lot.
    – s_ha_dum
    Jan 22, 2013 at 23:22

1 Answer 1


You can use the Transients API to cache the entire HTML output so the queries are not done every time the page is loaded:

$transient = 'my-300-posts';
$timeout   = 3600; // 1 hour

if ( false === $out = get_transient( $transient ) ) {

    $args = array( YOUR ARGS GO HERE );
    $posts = get_posts( $args );
    if ( $posts ) {
        foreach ( $posts as $post ) {
            $out .= get_the_title( $post->ID );
            $out .= // whatever else you want to output...

    if ( $out ) {
        set_transient( $transient, $out, $timeout );


echo $out;

However, you're still serving 300 post thumbnails on one page load, which is a lot of data to transfer.

(You also need to delete the transient on the save_post and delete_post hooks)

Maybe you'd be better off with infinite scrolling? It's an option in the Jetpack plugin.

  • 2
    Another viable option over infinite scroll is to use lazy-loaded images so that only visible images are actually loaded into the browser.
    – Bendoh
    Jan 22, 2013 at 23:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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