find custom post type post by searching its custom field with my string
-
22-04-2021 - |
Question
I have a custom post type called series
and each post has a custom field named originaltitle
. So in my code before I create a new post, I need to check if there is already a "series" with same originaltitle
custom field value.
If it exists, then return that post ID. If not, then I can move on with my code.
Any help is appreciated.
Solution
You can find the post using get_posts()
and the meta query (in my example, I used meta_key
and meta_value
) like so:
See the function reference for more details on the parameters (and other examples that might help you), but the 'fields' => 'ids'
means that the function will return only the post IDs and not full post object/data.
<?php
// Find a "series" post with the meta originaltitle set to a specific value.
$ids = get_posts( array(
'post_type' => 'series',
'post_status' => 'publish',
'posts_per_page' => 1,
'meta_key' => 'originaltitle',
'meta_value' => 'put value here',
'fields' => 'ids',
) );
$post_id = array_shift( $ids );
// Or you can do something like:
/*
if ( ! empty( $ids ) ) {
$post_id = $ids[0];
// run your code
}
*/
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange