【问题标题】:Get term names array from all product for a specific product attribute in Woocommerce从 Woocommerce 中特定产品属性的所有产品中获取术语名称数组
【发布时间】:2018-11-25 17:40:01
【问题描述】:

我正在尝试从所有产品中获取包含特定产品属性“颜色”的所有自定义术语的数组。

这是我的功能代码:

// custom_terms_taxonomy function

function custom_terms_taxonomy()
{
    $custom_terms = array();
    // array with products
    $products_array = array( 'post_type' => 'product', 'posts_per_page' => -1 );

        foreach ( $products_array as $product_array ) {
        // attribute string
        $terms_array = $product_array->get_attribute( 'pa_color' );
        // array with attributes
        $terms_array = ! empty($terms_array) ? (array) explode(', ', $terms_array) : array();

        foreach ( $terms_array as $term_array ) {
              // check if the value exist aleready in array
              if (!in_array($term_array, $custom_terms)) {
              // add attributes to Custom_array
              array_push($custom_terms,$term_array);
              }
           }
        }

   return $custom_terms;
}
//output
$att_array=custom_terms_taxonomy();
print_r($att_array);

这个脚本不起作用。任何帮助表示赞赏。

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy taxonomy-terms


    【解决方案1】:

    您的代码中存在一些错误和遗漏的内容……请尝试以下操作:

    // custom_terms_taxonomy function
    function custom_terms_taxonomy()
    {
        $custom_terms = array();
        // array with products
        $products = wc_get_products( array( 'status' => 'publish', 'limit' => -1 ) );
    
        foreach ( $products as $product ) {
            // attribute string
            $terms_names = $product->get_attribute( 'pa_color' );
            // array with attributes
            $terms_names_array = ! empty($terms_names) ? (array) explode(', ', $terms_names) : array();
    
            foreach ( $terms_names_array as $terms_name ) {
                // check if the value exist aleready in array
                if ( !in_array( $terms_name, $custom_terms ) ) {
                    // add attribute term name in the array
                    $custom_terms[] = $terms_name;
                }
            }
        }
    
       return $custom_terms;
    }
    
    // Raw output
    print_r(custom_terms_taxonomy());
    

    经过测试并且有效。

    【讨论】:

    • 完美运行!
    猜你喜欢
    • 2020-11-02
    • 2018-10-11
    • 2017-03-27
    • 1970-01-01
    • 2021-06-07
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    相关资源
    最近更新 更多