获取 WooCommerce 中价格最高的一系列独特产品 attributes/values

Get an array of unique product attributes/values with the highest price in WooCommerce

在 WooCommerce 中,我想:

  1. 获取特定产品属性的唯一值(来自我的所有产品),假设所有产品都将该特定属性设置为某物。

  2. 获取产品价格最高的唯一属性值列表。

例如:

产品 1:
产品属性 = 绿色
价格 = 100 美元

产品 2:
产品属性 = 红色
价格 = 50 美元

产品 3:
产品属性 = 绿色
价格 = 50 美元

Expected result (an array):

Green : 0
Red :

关于如何对此进行编码以使其 returns 成为数组的任何想法?

对于数组中具有最高变化价格的可变产品及其变化属性名称和术语值名称,您将尝试以下自定义函数:

function get_variations_attributes_values_highest_price(){
    global $wpdb;

    // SQL query
    $all_attributes = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}woocommerce_attribute_taxonomies");
    $product_attributes = array();
    foreach( $all_attributes as $value ){
        $product_attributes = 'pa_'.$value->attribute_name;
    }
    //$pa_taxonomies = "'".implode("','", $product_attributes)."'";

    // The 2nd SQL query
    $query = $wpdb->get_results( "
        SELECT p.ID, pm.meta_key as attr, pm.meta_value as term, pm2.meta_value as price
        FROM {$wpdb->prefix}postmeta as pm
        INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
        INNER JOIN {$wpdb->prefix}postmeta as pm2 ON pm.post_id = pm2.post_id
        WHERE p.post_type IN ('product_variation','product')
        AND p.post_status LIKE 'publish'
        AND pm.meta_key LIKE 'attribute_pa_%'
        AND pm2.meta_key LIKE '_price'
        AND pm2.meta_value != ''
        ORDER BY pm.meta_key ASC, pm.meta_value ASC, CAST(replace(pm2.meta_value, 'MDT ', '') AS UNSIGNED) ASC
    " );
    //print_pr($query);

    $ordered_results = $results = array();

    // Loop 1: Filtering and removing duplicate terms keeping highest price
    foreach( $query as $values ){
        if( !empty($values->price)){
        $filter_key = $values->attr .' '.$values->term;
            $ordered_results[$filter_key] = (object) array( 'attr' => $values->attr,
                'term' => $values->term, 'price' => $values->price );
        }
    }

    // Loop 2: Get the real name values, formatting data
    foreach( $ordered_results as $result ){
        $taxonomy = str_replace('attribute_' , '', $result->attr );
        $attr_name = get_taxonomy( $taxonomy )->labels->singular_name; // Attribute name
        $value_name = get_term_by( 'slug', $result->term, $taxonomy )->name; // Attribute value term name
        $results[$attr_name.' - '.$value_name] = wc_price($result->price);
    }
    return $results; 
}

代码进入活动子主题(或活动主题)的 function.php 文件。

已测试并有效。


## --- USAGE --- ##

// RAW ARRAY OUTPUT
echo '<pre>'; print_r(get_variations_attributes_values_highest_price()); echo '</pre>';

您可以轻松地进行一些小改动来满足您的需求(TheBear 的蜂蜜)