检查元密钥值是否已存在

时间:2013-11-04 作者:SomeoneS

比方说,我有几个帖子带有元键“videoid”。每个帖子的元键的值都不同(而且必须不同)。添加新帖子时,如何检查某些旧帖子是否已经存在具有该确切值的videoid?我将此用作将自定义元框添加到WP管理区域的参考:http://codex.wordpress.org/Function_Reference/add_meta_box

4 个回复
最合适的回答,由SO网友:Nicolai Grossherr 整理而成

只需使用WP_Query 使用Custom Field parameters (meta_query) 要查找带有元键和值的帖子-示例代码:

 // 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
 }
没有必要使用query_post() - 请参见: When should you use WP_Query vs query_posts() vs get_posts()? . 如果需要一个完整的post对象数组,而不仅仅是ID,请删除\'fields\' => \'ids\'.

SO网友:jetlej

ialocin的回答错误地指出,存储为变量的wp\\u查询只会吐出一个ID数组。相反,它会给出整个wp\\u查询对象,因此您必须使用->posts来获取该post ID数组。

// args to query for your key
 $args = array(
   \'post_type\' => \'YOUR_POST_TYPE\',
   \'meta_query\' => array(
       array(
           \'key\' => \'YOUR_META_FIELD_NAME\',
           \'value\' => \'111\'
       )
   ),
   \'fields\' => \'ids\'
 );
 // perform the query
 $query = new WP_Query( $args );
 $duplicates = $query->posts;

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

SO网友:cscheltinga

或者将其封装在函数中:

function meta_value_exists($your_meta_value) {
    $args = array(
        \'post_type\'   => \'YOUR_POST_TYPE\',
        \'post_status\' => \'publish\',
        \'numberposts\' => 1,
        \'meta_key\'     => \'your_meta_field\',
        \'meta_value\'   => $your_meta_value,
    );
    $current_post = get_posts($args);
    if( $current_post ) {
        return true;
    } else {
        return false;
    }
}
因此,您可以检查您的元值:

$video_id = 1234;
if(meta_value_exists($video_id){
   // do something if exists
} else {
   // do something if not exists
}

SO网友:SomeoneS

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;
结束

相关推荐

WordPress:可排序的Metabox字段不保存位置

我遇到了一个让我困惑的问题:升级到WP 3.6后,当您重新订购时,我的可排序metabox字段没有保存它们的位置。下面是我的代码:PHP:function save_box( $post_id ) { $post_type = get_post_type(); // verify nonce if ( ! isset( $_POST[\'custom_meta_box_nonce_field\'] ) ) return $p