PHP如何使用数组中的变量

标签 php arrays wordpress

我的 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/

相关文章:

php - mysql 序列事件无法正常运行!

php - MySQL PHP SELECT WHERE id 等于最大

c# - 要构造的字节数组

javascript - 如何根据Javascript中的特定条件从数组中删除一行

数组存储20个数,然后显示最高、最低、总数和平均值

php - 在 WHERE 条件下使用 BETWEEN

php - 如何在 CodeIgniter 中将两个数组合并为一个?

mysql - 使用 mysqli_connect() 将 Wordpress 连接到 Google App Engine 上的 Cloud SQL

php - 在 Woocommerce 中的购物车和结帐之间添加新步骤

html - Safari 在底部切断固定图像?