WooCommerce - 按销售自定义计算订购相关产品

时间:2016-09-11 12:23:37

标签: php wordpress woocommerce custom-fields product

Woocommerce相关产品模板位于:

/wp-content/plugins/woocommerce/templates/single-product/related.php

但目前按随机排序。

我想通过 'total_sales' + 'sales_count' (那些是2个meta_keys保存整数值而 'sales_count' 是另外的自定义字段)。

以下是查询:

 $args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
    'no_found_rows'        => 1,
    'posts_per_page'       => 4,
    'orderby'   => 'total_sales',
     'order' => 'DESC',
    'post__in'             => $related
) );
    $products = new WP_Query( $args );

以上查询排序产品购买 total_sales ,但我需要使用 total_sales sales_count 的总和对其进行排序?

有没有办法做到这一点?

由于

1 个答案:

答案 0 :(得分:1)

  

我不太了解 $soldty = get_post_meta( $product->id, 'sales_count', true ); 的目的,因为产品的默认 'total_sales' 已经所有已售商品的计算(每次销售的商品数量都会增加)。

无论如何,如果你真的需要这个计算,最好的选择是制作一个函数,为每个产品创建/更新一个新的自定义字段,并进行计算:

add_action( 'wp_loaded', 'products_update_total_sales_calculation' );
function products_update_total_sales_calculation(){
    $sales = array();
    $all_products = get_posts( array(
        'post_type'            => 'product',
        'post_status'          => 'publish',
        'posts_per_page'       => -1,
    ) );
    foreach($all_products as $item) {
        $units_sold = get_post_meta( $item->ID, 'total_sales', true );
        $soldty = get_post_meta( $item->ID, 'sales_count', true );
        if(empty($soldty)) $soldty = 0;
        $result = $units_sold + $soldty;
        update_post_meta( $item->ID, 'global_sales_count', $result );
    }
}

此功能可以计算产品销售额,并使用其中的计算值创建/更新自定义字段 'global_sales_count'

现在,您可以根据以下新自定义字段自定义查询 'orderby' 参数:

$args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
    'no_found_rows'        => 1,
    'posts_per_page'       => 4,
    'meta_key'             => 'global_sales_count', // <== <== the new custom field
    'orderby'              => 'meta_value_num',
    'order'                => 'DESC',
    'post__in'             => $related

) );
    $products = new WP_Query( $args );

如果您不需要计算,'meta_key'值将更改为现有 'total_sales' 产品 meta_key ,这样:

$args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
    'no_found_rows'        => 1,
    'posts_per_page'       => 4,
    'meta_key'             => 'total_sales', // <== <== the existing meta_key 
    'orderby'              => 'meta_value_num',
    'order'                => 'DESC',
    'post__in'             => $related

) );
    $products = new WP_Query( $args );