我正在尝试按可用总存量对产品页面和产品代码进行排序。
当前,我正在我的function.php上使用此功能,但它仅适用于在变体级别管理的简单产品而非可变产品。
/ *从低到高的库存默认顺序* /
add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby');
function am_woocommerce_catalog_orderby( $args ) {
$args['orderby'] = 'meta_value_num';
$args['order'] = 'asc';
$args['meta_key'] = '_stock';
// error_log("query of the catalog!",0);
return $args;
}
总有没有对每种产品变体的总数量进行分组或汇总,然后根据该值进行排序?
我已经找了几天,找不到最接近this post的解决方案,但这对我的情况没有帮助。
我还要使用以下代码来显示对此post中找到的每种产品的库存总量:
add_action('woocommerce_after_shop_loop_item','replace_add_to_cart');
function replace_add_to_cart() {
global $wpdb, $product;
$link = $product->get_permalink();
echo do_shortcode('[button link="' . esc_attr($link) . '"]View Details[/button]');
$product_id = $product->get_id();
$count_in_stock = 0;
/* Slower
if ( $product->is_type( 'variable' ) ) {
$variation_ids = $product->get_children(); // Get product variation IDs
foreach( $variation_ids as $variation_id ){
$variation = wc_get_product($variation_id);
if( $variation->is_in_stock() )
$count_in_stock++;
}
}
*/
// Quicker faster
if ( $product->is_type( 'variable' ) ) {
$count = $wpdb->get_col("
SELECT count(p.ID) as in_stock_count FROM {$wpdb->prefix}postmeta as pm
INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
WHERE p.post_type LIKE 'product_variation' AND p.post_parent = $product_id
AND pm.meta_key LIKE '_stock_status' AND pm.meta_value LIKE 'instock'
");
$count_in_stock = reset($count);
}else{
$count_in_stock = $product->get_stock_quantity();
}
// Your condition
if( $count_in_stock > 0 ){
echo "<center>Spots : <span class='instock' id='" . $count_in_stock."'>".$count_in_stock."</span></center>";
}
}
see screenshot,这很不言自明。期望的结果是像屏幕截图一样,先得到2、9然后21,而不是9,21,2。
感谢您的帮助!