WordPress – Meta query with post id

Can I add ID to the $args array? I need to check if the key value pair custom field exists for a particular post. Now it checks if the key value pair exists in any post. Or do I need to perform the query and then check for my value in the returned array?

    $args = array(
     'post_type' => 'post',
     'post_status' => 'publish',
     'ID' => $_POST['post_id'],
     'meta_query' => array(
             array(
                     'key' => 'claim',
                     'value' => $user_ID
             )
     )
    );

    // perform the query
    $query = new WP_Query( $args );
    $vid_ids = $query->posts;

    if ( empty( $vid_ids ) ) {
         add_post_meta( $_POST['post_id'], 'claim', $user_ID );
    }else{
        echo "sorry";
    }

Related posts

2 comments

  1. Please reference the Codex entry for post/page parameters for WP_Query().
    You can pass single post id with this

    $query = new WP_Query( array( 'p' => 7 ) );
    

    If you want to pass multiple post id’s use

     $myarray = array('100', '222');
    
    $args = array(
       'post_type' => 'post',
       'post__in'      => $myarray
    );
    // The Query
    $the_query = new WP_Query( $args );
    
  2. Use get_post_meta to get custom field value for your object.

    $claims=get_post_meta($ID,'claim');
    $exists=false;    
    if(count($claims)>0)
    {
        foreach($claims as $claim)   
        {
            if($claim==$user_ID)
            {
                $exists=true;
                break;
            }
        } 
    }
    if(!$exists)
    {
        add_post_meta( $_POST['post_id'], 'claim', $user_ID );
    }
    

Comments are closed.