假设您有变量来保存每个变量的自定义值:
$category
$tag
$author
$search
然后只需创建一个参数数组,并有条件地向其中添加键:
$custom_query_args = array(
// Set any default args here
// NOTE: This is where you\'d add
// things like pagination (posts_per_page),
// order/sort parameters, and the like
\'posts_per_page\' => 10,
\'orderby\' => \'date\',
\'order\' => \'DESC\'
);
// If user defines $category, add it
if ( \'\' != $category ) {
$custom_query_args[\'cat\'] = $category;
}
// If user defines $tag, add it
if ( \'\' != $tag ) {
$custom_query_args[\'tag\'] = $tag;
}
// If user defines $author, add it
if ( \'\' != $author ) {
$custom_query_args[\'author\'] = $author;
}
// If user defines $search, add it
if ( \'\' != $search ) {
$custom_query_args[\'s\'] = $search;
}
// Run the query
$custom_query = new WP_Query( $custom_query_args );
注意:如何定义
$category
,
$tag
,
$author
, 和
$search
超出了此答案的范围。
假设(用户定义)$post_meta_key
和(静态)$post_meta_key
:
// If user defines $post_meta_value, add it
if ( \'\' != $post_meta_value ) {
$custom_query_args[\'meta_query\'] = array(
array(
\'key\' => $post_meta_key,
\'value\' => $post_meta_value,
\'compare\' => \'=\',
)
);
}