WordPress在get_posts或WP_Query方法中,活用meta_query,可以变换出无数种高级检索,是WordPress的入门技能。
最简单的用法,查询自定义字段“post_color”值为“red”的文章
$arr = array(
'post_type', => 'post',
'meta_key' => 'post_color',
'meta_value' => 'red'
);
$myPosts = new WP_Query( $arr ); |
$arr = array(
'post_type', => 'post',
'meta_key' => 'post_color',
'meta_value' => 'red'
);
$myPosts = new WP_Query( $arr );
引入meta_compare参数,查询自定义字段“post_color”值不为“red”的文章
$arr = array(
'post_type', => 'post',
'meta_key' => 'post_color',
'meta_value' => 'red',
'meta_compare' => '!='
);
$myPosts = new WP_Query( $arr ); |
$arr = array(
'post_type', => 'post',
'meta_key' => 'post_color',
'meta_value' => 'red',
'meta_compare' => '!='
);
$myPosts = new WP_Query( $arr );
推荐写法
下面开始进阶用法,首先要换一种写法,把所有自定义字段相关的参数都打包到meta_query参数中,效果和上面一段一样:
$arr = array(
'post_type', => 'post',
'meta_query'=> array(
'key' => 'post_color',
'value' => 'red',
'compare' => '!='
)
);
$myPosts = new WP_Query( $arr ); |
$arr = array(
'post_type', => 'post',
'meta_query'=> array(
'key' => 'post_color',
'value' => 'red',
'compare' => '!='
)
);
$myPosts = new WP_Query( $arr );
查看详细 »