Update product order by category order
// Update menu_order when add new
add_action( 'woocommerce_new_product', 'tzn_woocommerce_new_product_update_menu_order_by_category', 10, 1 );
add_action( 'woocommerce_update_product', 'tzn_woocommerce_new_product_update_menu_order_by_category', 10, 1 );
if ( ! function_exists( 'tzn_woocommerce_new_product_update_menu_order_by_category' ) ) {
function tzn_woocommerce_new_product_update_menu_order_by_category( $product_id ) {
//$product = wc_get_product( $product_id );
$terms = get_the_terms( $product_id, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
break;
}
$args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
);
$all_categories = get_categories( $args );
$i = 0;
foreach ($all_categories as $cat) {
if($product_cat_id == $cat->term_id){
wp_update_post(
array(
'ID' => $product_id,
'menu_order' => $i
)
);
break;
}
$i++;
}
}
}
// Script update menu_order products by Category
add_action('init', 'tzn_update_product_menu_order');
if ( ! function_exists( 'tzn_update_product_menu_order' ) ) {
function tzn_update_product_menu_order(){
if(current_user_can('administrator') && isset($_GET['update_product_menu_order']) && $_GET['update_product_menu_order'] == "1"){
$args = array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
);
$all_categories = get_categories( $args );
$i = 0;
foreach ($all_categories as $cat) {
$query = new WC_Product_Query( array(
'limit' => -1,
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $cat->slug,
)
),
) );
$products = $query->get_products();
if($products && count($products ) > 0){
foreach($products as $product_id){
$product = wc_get_product($product_id);
echo "<br>-- product_id: ".$product_id;
wp_update_post(
array(
'ID' => $product_id,
'menu_order' => $i
)
);
update_post_meta( $product_id, 'update_product_menu_order', 1 );
echo "updated";
}
}
$i++;
}
}
}
}