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?
有办法做到这一点吗?
谢谢
我不太理解
$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 );