【问题标题】:Get list of slugs for a specific product attribute on archive pages in Woocommerce在 Woocommerce 的存档页面上获取特定产品属性的 slug 列表
【发布时间】:2018-11-28 06:27:42
【问题描述】:

我需要根据一组成分(这是 Woo 产品属性)在产品概览(类别、存档)页面上显示一些自定义图标。

我正在使用woocommerce_after_shop_loop_item_title,这是展示我想要的东西的正确地方。但是,我无法轻松获得属性的 slug 列表。我的目标是获得一系列类似 ['onion', 'fresh-lettuce', 'cheese'] 或其他的 slug。

我目前的尝试是这样的:

add_filter( 'woocommerce_after_shop_loop_item_title', function () {
    global $product;
    $attrs = $product->get_attributes();
    $slugs = $attrs->get_slugs( 'ingredients' );
    var_dump( $slugs );
});

但这不起作用。

请注意,$product->get_attributes() 有效,但对于类别页面上的每个产品都是相同的。

请指教!

【问题讨论】:

    标签: php wordpress woocommerce product custom-taxonomy


    【解决方案1】:

    使用WC_Product get_attribute() 方法尝试以下操作:

    add_filter( 'woocommerce_after_shop_loop_item_title', 'loop_display_ingredients', 15 );
    function loop_display_ingredients() {
        global $product;
        // The attribute slug
        $attribute = 'ingredients';
        // Get attribute term names in a coma separated string
        $term_names = $product->get_attribute( $attribute );
    
        // Display a coma separted string of term names
        echo '<p>' . $term_names . '</p>';
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。


    现在,如果您想在逗号分隔列表中获取术语 slugs,您将使用以下内容:

    // The attribute slug
    $attribute = 'ingredients';
    // Get attribute term names in a coma separated string
    $term_names = $product->get_attribute( $attribute );
    
    // Get the array of the WP_Term objects
    $term_slugs = array();
    $term_names = str_replace(', ', ',', $term_names);
    $term_names_array = explode(',', $term_names);
    if(reset($term_names_array)){
        foreach( $term_names_array as $term_name ){
            // Get the WP_Term object for each term name
            $term = get_term_by( 'name', $term_name, 'pa_'.$attribute );
            // Set the term slug in an array
            $term_slugs[] = $term->slug;
        }
        // Display a coma separted string of term slugs
        echo '<p>' . implode(', ', $term_slugs); . '</p>';
    }
    

    【讨论】:

    • 谢谢!代码 sn-p 效果很好。我很惊讶 Woo 没有内置功能来执行此操作……似乎产品上的内置 get_attribute 方法已经获取所有术语并将它们手动粘合在一起。无论如何,您的代码都是正确的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多