我的 WordPress 主题中有一个选项页面,用于从自定义分类中选择多个类别。
$terms_obj = get_option('shop_features')
这将返回一个数组,其中 $key 为类别名称,$value 为 1 或空,具体取决于类别是否被选中。
我需要获取已检查类别的列表,以便在另一个函数的数组中使用:
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'knives' ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
我需要插入变量 $terms 中包含的类别名称,以将 'terms' => array('knives')
替换为 'terms' => 数组 ( $条款)
只是这样做是行不通的!
以下是我尝试实现这一目标的方法:
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$terms_obj = of_get_option( 'eco_shop_features', $default );
foreach ( $terms_obj as $slug => $checked ) { //$key ==> value
if ( $checked > 0 )
$terms .= '\'' . $slug . '\', ';
}
$terms = rtrim( $terms, ', ' );
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( "$terms" ), // Don't display products in the knives category on the shop page
'operator' => 'NOT IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}
我不知道如何将类别名称列表插入到术语字段中,以便它作为数组使用。
最佳答案
正确的方法似乎被您注释掉了,下面应该可行
foreach ( $terms_obj as $slug => $checked ) { //$key ==> value
if ( $checked > 0 )
$terms[] = $slug;
}
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $terms,
'operator' => 'NOT IN'
)));
关于PHP如何使用数组中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21848614/