Skip to content
Advertisement

WordPress Find ID of a Post with a specific meta value

I have about 25,000 posts here (and rising). All of them under a Custom Post Type “lead”. Each post has meta information, including a variable called “uniqid”. this uniqid is a url parameter. now i need the post id where exactly this uniqid exists.

Now my question is if there is a way to speed up this determination.

I have tried 2 ways once a wp_query and get_results.

I ask because this function that determines the post id is always noted by plugin “query monitor” that it is slow.

These are the 2 approaches, both work. I just wonder if it is possible to speed up here?

The WP_Query solution.

$post_id = false;
$args = array(
    'posts_per_page'    =>  -1,
    'post_type'         =>  'lead',
    'fields' => 'ids',
    'orderby' => 'date',
    'order'   => 'ASC',
    'post_status'       =>  'publish',
    'meta_key'          => 'uniqid',
    'meta_value'        => $uniqid
);

$query = new WP_Query( $args );


if( $query->have_posts() ) {
    while( $query->have_posts() ) {
        $query->the_post();

        // Get Post ID for return
        $post_id = get_the_id();

        // Break loop, when matching id was found       
        $uniqidGPM = get_post_meta( $post_id, 'uniqid' , true );

        if($uniqidGPM == $uniqid) {
            $post_found = true;
            break;
        }

    }
}

wp_reset_postdata();
return $post_id;

The select get_results solution.

$post_id = false;
global $wpdb;

$selectQuery = "SELECT wp_wkdm_posts.ID FROM wp_wkdm_posts  INNER JOIN wp_wkdm_postmeta ON ( wp_wkdm_posts.ID = wp_wkdm_postmeta.post_id ) WHERE 1=1  AND ( ( wp_wkdm_postmeta.meta_key = 'uniqid' AND wp_wkdm_postmeta.meta_value = '".$uniqid."' )) AND wp_wkdm_posts.post_type = 'lead' AND ((wp_wkdm_posts.post_status = 'publish')) GROUP BY wp_wkdm_posts.ID ORDER BY wp_wkdm_posts.post_date ASC";
$selectQueryResult = $wpdb->get_results($selectQuery);

if (empty($selectQueryResult)) {
    return $post_id;
}else{
    $post_id = $selectQueryResult[0]->ID;
    return $post_id;
};

Advertisement

Answer

Please use this meta_query condition on the same query, it helps you.

$args = array(
    'post_type' => 'lead',
    'posts_per_page'    =>  -1,
    'post_status'       =>  'publish',
    'meta_query' => array(
        'key' => 'uniqid',
        'value' => 'YOUR_VALUE'
    )
);

$query = new WP_Query($args);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement