【问题标题】:Wordpress use array key and value to set data attributeWordpress 使用数组键和值来设置数据属性
【发布时间】:2013-11-22 12:47:27
【问题描述】:

我已经设置了一个产品值数组。我需要将每个数组键设置为数据属性并将值设置为数据属性值

<li data-name="product1" data-price="49.99" data-rating="4.5"></li>

所以在 Wordpress 中我有这个过滤器钩子

function product_data_sorting( $product_attrs, $product, $terms) {
    global $post;

    // Product Attributes
    $product_attrs['name']  = $post->post_name;
    $product_attrs['price']     = $product->price;
    $product_attrs['rating']    = $product->get_average_rating();
    $product_attrs['newness']   = $post->post_modified;

    // Product Categories
    foreach ($terms as $term) {
        $categories[]  = $term->slug;
    }
    $product_attrs['categories'] = $categories;


    foreach ($product_attrs as $attribute) {
        if ( is_array($attribute) ) {
            //This is a category
        }
        else {
            $results[] = 'data-' . $key . '="' . '$attribute' . '"';
        }   
    }
    return $results
}
add_filter( 'add_sorting', 'product_data_sorting', 10, 3 );

我将所有正确的数据推送到我需要的 $product_attrs 数组中,但不确定如何使用数组键和值,以便在 $results 数组中将其格式化如下:

$results = (data-name="product1", data-price="49.99", data-rating="4.5");

希望这有点道理

谢谢

【问题讨论】:

    标签: arrays wordpress key


    【解决方案1】:

    您需要在foreach 中对key=>value

    $ignored = array ('newness'); // array to maintain what attributes you want to ignore
    
         foreach ($product_attrs as $key => $attribute) {
                if ( is_array($attribute) ) {
                    //This is a category
                }
                else {
                   if(!inarray($key, $ignored) 
                      $results[] = 'data-' . $key . '="' . $attribute . '"';
                }   
         }
    

    另请注意,$attribute 没有像您在问题中那样用单引号括起来。单引号内的变量无法解析

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 2017-01-23
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      相关资源
      最近更新 更多