Let’s say that I have few posts with meta key “videoid”. Value of that meta key is different for every post (and has to be different). When adding new post, how can I check if videoid with that exact value already exist for some older posts? I used this as a refference for adding custom meta box to admin area of WP: http://codex.wordpress.org/Function_Reference/add_meta_box
4 Answers
Just do a query with WP_Query
using the Custom Field parameters (meta_query
) to look for posts with the meta key and the value – exemplary code:
// args to query for your key
$args = array(
'post_type' => 'your_post_type',
'meta_query' => array(
array(
'key' => 'videoid',
'value' => $new_posts_videoid // for example: '111'
)
),
'fields' => 'ids'
);
// perform the query
$vid_query = new WP_Query( $args );
$vid_ids = $vid_query->posts;
// do something if the meta-key-value-pair exists in another post
if ( ! empty( $vid_ids ) ) {
// do your stuff
}
There is no need to use query_post()
– see:
When should you use WP_Query vs query_posts() vs get_posts()?
. If you need a complete array of post objects, not just the ids, remove 'fields' => 'ids'
.