我正在寻找一种方法来显示属于特定类别的帖子or 如果他们有自定义字段。如果我同时指定这两个参数\'cat\' => \'9\'
和\'meta_key\' => \'featured\'
然后在查询参数中WP_Query
返回同时满足这两个条件的帖子。
我不想要的。我需要的是显示文章,如果他们有类别9
或者如果他们有自定义字段featured
.
如果没有意义,请告诉我。我会贴一个例子来解释。
我正在寻找一种方法来显示属于特定类别的帖子or 如果他们有自定义字段。如果我同时指定这两个参数\'cat\' => \'9\'
和\'meta_key\' => \'featured\'
然后在查询参数中WP_Query
返回同时满足这两个条件的帖子。
我不想要的。我需要的是显示文章,如果他们有类别9
或者如果他们有自定义字段featured
.
如果没有意义,请告诉我。我会贴一个例子来解释。
您可以尝试自定义_meta_or_tax
中的参数WP_Query
(PHP 5.4以上):
$args = [
\'post_type\' => \'post\',
\'_meta_or_tax\' => true, // <-- our new custom parameter
\'tax_query\' => [...], // <-- our tax query
\'meta_query\' => [...], // <-- our meta query
];
$query = new WP_Query( $args );
我们使用以下插件来支持此自定义参数:/**
* Modify WP_Query to support \'meta_or_tax\' argument
* to use OR between meta- and taxonomy query parts.
*/
add_filter( \'posts_where\', function( $where, \\WP_Query $q )
{
// Get query vars
$tax_args = isset( $q->query_vars[\'tax_query\'] )
? $q->query_vars[\'tax_query\']
: null;
$meta_args = isset( $q->query_vars[\'meta_query\'] )
? $q->query_vars[\'meta_query\']
: null;
$meta_or_tax = isset( $q->query_vars[\'_meta_or_tax\'] )
? wp_validate_boolean( $q->query_vars[\'_meta_or_tax\'] )
: false;
// Construct the "tax OR meta" query
if( $meta_or_tax && is_array( $tax_args ) && is_array( $meta_args ) )
{
global $wpdb;
// Primary id column
$field = \'ID\';
// Tax query
$sql_tax = get_tax_sql( $tax_args, $wpdb->posts, $field );
// Meta query
$sql_meta = get_meta_sql( $meta_args, \'post\', $wpdb->posts, $field );
// Modify the \'where\' part
if( isset( $sql_meta[\'where\'] ) && isset( $sql_tax[\'where\'] ) )
{
$where = str_replace(
[ $sql_meta[\'where\'], $sql_tax[\'where\'] ],
\'\',
$where
);
$where .= sprintf(
\' AND ( %s OR %s ) \',
substr( trim( $sql_meta[\'where\'] ), 4 ),
substr( trim( $sql_tax[\'where\'] ), 4 )
);
}
}
return $where;
}, PHP_INT_MAX, 2 );
这是对我答案的一种未经检验的简化here.我正在制作一个小部件,我使用了wp_dropdown_categories() 功能。我搞不懂的是如何从下拉列表中获取所选值。所选变量存储在哪个变量中?$args = array(\'show_option_none\' => \'No Category\',\'hide_empty\' => 0); wp_dropdown_categories( $args );