Sort WooCommerce store products based on inventory
Sort WooCommerce store products based on inventory
I use this code to sort the inventory of a WordPress store. This code has two problems
1. Instead of calculating the product inventory numerically, it puts it into an array and therefore cannot properly sort the products based on the inventory.
2. If the code is active, it will not show the new added products.
add_action('init', function() {
if( isset($_GET['update_products_arv']) ) {
$products = wc_get_products( [ 'limit' => 500,'offset' => 200] );
foreach( $products as $product ){
$total_stock = $product->get_stock_quantity() ? : 0;
if( $product->is_type( 'variable' ) ){
$variations = $product->get_children();
if( !$variations ) continue;
foreach ($variations as $variation_id) {
$variation = wc_get_product( $variation_id );
$total_stock += $variation->get_stock_quantity() ? : 0;
}
}
update_post_meta($product->get_id(), 'nsaeidi_stock', $total_stock);
}
}
});
add_action('woocommerce_product_query', function($q) {
if( ! is_admin() ) {
$q->set('orderby', 'meta_value_num');
$q->set('meta_key', 'nsaeidi_stock');
$q->set('order', 'DESC');
}
});
Please tell me how to modify the code?
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand