I mean the speed of query records from database, not the way we render the content gained. More specifically, I just want to query the posts' IDs, my site contains more than 4000 posts (they are custom post type) and I just want to have all their ID.


Yes, custom SQL queries are in essence faster than a custom instance of WP_Query. The disadvantage of a custom SQL query is that you are loosing a lot, like object cache, filters and actions, etc, etc, and it is also discouraged to use custom SQL if Wordpress already offers that specific functionality.

WP_Query does have the option however to only query post ID's (which is really fast and very lean) by means of adding and using the fields parameter in your query arguments. You can also just use get_posts which uses WP_Query but does not return the post object but just the array of posts

So, you can basically do the following

$args = [
    'nopaging' => true,
    'fields' => 'ids' // Just get post ID's
$q = get_posts( $args );
var_dump( $q );

Here is an example of how to cache a custom SQL.

     function get_sample_data() {
        global $wpdb;

            = "
            SELECT  ID ,post_title
            FROM $wpdb->posts
            LEFT JOIN $wpdb->postmeta ON($wpdb->posts.ID = $wpdb->postmeta.post_id)
            WHERE $wpdb->posts.post_status = 'publish' 
            AND $wpdb->posts.post_type = 'sample_type'
            AND $wpdb->postmeta.meta_key = '_sample_meta_key'
            AND $wpdb->postmeta.meta_value = 'singular'
            ORDER BY $wpdb->posts.post_date ASC

        $result = wp_cache_get( 'sample_cache_key' );
        if ( false === $result ) {
            $result = $wpdb->get_results( $query );
            wp_cache_set( 'sample_cache_key', $result );

        return $result;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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