简体   繁体   中英

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";
    }

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 );

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 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM