Will McLean
Process diary

Using a direct SQL query in place of the wp_query loop

Last modified: November 3, 2017
Created: August 17, 2017

Recently at Pollen, we had to deal with a list of 16000 posts. These were locations around Australia and we had to load them all into a select drop-down menu as options. We needed to grab their slug and their title as value and label respectively. We originally did this with a wp_query loop however when we install all the locations, whilst it worked (slowly) on the server, it was unusable on our local machines. For that reason, we decided to use our own query directly on the database. This means it isn’t running through all the WordPress functions that are not relevant to our particular scenario thus increasing the speed of the query drastically.

Previous loop

$wp_query = new WP_Query( array( 'post_type' => 'locations', 'order' => 'ASC', 'orderby' => 'title', 'nopaging' => true ) ); 
        while ($wp_query->have_posts()) : $wp_query->the_post();
            echo basename( get_the_permalink() );
    rewind_posts() ?> 

New loop

    $sql = $wpdb->prepare( "
        SELECT post_title, post_name
        FROM wp_posts
        WHERE post_type = %s
        ", 'locations');
    $results = $wpdb->get_results( $sql );
    foreach( $results as $result ):
        echo $result->post_name;
        echo $result->post_title;

This is a Knowledge Base post.