Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
1  
Which plugin did you use? Please edit your question and add a link. Sidenote: Questions are meant to be references for later visitors as well. Please rework your questions spelling/punctuation/grammar/capitalization so it as as easy to read as possible. Thanks. –  kaiser Nov 4 '13 at 12:39
    
I wanted to say that I used that code (on that link), in my own plugin. Never mind, deleted that part. –  SomeoneS Nov 4 '13 at 12:58

2 Answers 2

up vote 2 down vote accepted

Just do a query with WP_Query using the Custom Fields Parameter - 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' => '111'
       )
   ),
   'fields' => 'ids'
 );
 // perform the query
 $q_vid = new WP_Query( $args );

 // you are getting back an array of ids if the key has the same value at another post
 // otherwise it should be empty, but for failsafe reasons we're going to filter out
 // all keys with null, false and empty values, with array_filter(), just to be thorough
 $q_vid = array_filter( $q_vid );

 // do something if the key-value-pair exists in another post
 if ( ! empty( $q_vid ) ) {
     // do your stuff
 }

There is no need to use query_post() - actually there (almost) never is, see: When should you use WP_Query vs query_posts() vs get_posts()? . If you need a complete query object, not just the ids, remove 'fields' => 'ids'.

share|improve this answer

Found it:

$args = array(
    'meta_query' => array(
        array(
            'key' => 'videoid',
            'value' => $_POST['videoid']
        )
    )
);

$videoQuery = new WP_Query( $args ); 

if ( $videoQuery->have_posts() ) :
    while ( $videoQuery->have_posts() ) : 
            $videoQuery->the_post(); ?>
    echo "<h3 class='post-title'>" . the_title() . "</h3>";
    endwhile; 
    endif;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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