Using a direct SQL query in place of the wp_query loop
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.
$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() ); the_title() endwhile; rewind_posts() ?>
$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; endforeach;