仅查询已设置自定义字段的返回帖子

时间:2016-09-29 作者:Rod0n

我创建了一个自定义字段“entity\\u person\\u相关性”,范围从1到3,以便按相关性对结果进行排序。问题是已经有300多篇帖子,下面的查询仅显示设置了此自定义字段的帖子:

$query = ( array (
        \'post_type\'      => \'entity\',
        \'posts_per_page\' => 20,
        \'meta_query\'     => array(
            array(
                \'key\'       => \'entity_person_profile_type\',
                \'value\'     => $term->term_id,
                \'compare\'   => \'=\'
            )
        ),
        \'orderby\'  => \'meta_value_num\',           
        \'meta_key\' => \'entity_person_relevance\', 
        \'order\'    => \'DESC\',
        \'paged\'    => $paged
        )
);
我还想显示没有设置自定义字段的帖子。

2 个回复
SO网友:Benoti

您可以将自定义字段添加到所有帖子中:

$posts = get_posts(array(\'post_type\'=>\'entity\', \'posts_per_page\'=>-1);

foreach($posts as $post){
    if(get_post_meta($post->ID, \'entity_person_relevance\', true) == null ){
        $term = wp_get_object_terms( $post->ID, \'yourtermcat\'); // see codex to $wp_error handling or just set $term to 1, 2 or 3 

        update_post_meta($post->ID, \'entity_person_relevance\', $term->term_id); 
    }

}

SO网友:vancoder

将代码的meta\\u query部分更改为以下内容(未测试):

\'meta_query\'     => array(
        \'relation\' => \'OR\',
        array(
            \'key\'     => \'entity_person_profile_type\',
            \'value\'   => $term->term_id,
            \'compare\' => \'=\'
        ),
        array(
            \'key\'     => \'entity_person_profile_type\',
            \'compare\' => \'NOT EXISTS\'
        ),
    ),