WordPress “Loop” with large set of results

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.

Related posts

Leave a Reply

1 comment

  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.