Answer the question
In order to leave comments, you need to log in
How to programmatically call the recalculation of products in categories?
Hello. WPML has one bug that they've been well aware of for years, but they don't seem to have done anything about it. The problem is that in minor languages it fails to count the number of products within the categories, and as a result, the entire hierarchy in the categories widget flies. Here are 2 screenshots:
WPML itself offers to simply run the recalculation of terms from the admin panel. However, this all crashes every time a product is created/updated.
I wrote a function and hung it on the update/create new product hooks
add_action('woocommerce_update_product', 'recount_wc_terms_wpml', 99);
add_action('woocommerce_new_product', 'recount_wc_terms_wpml', 99);
function recount_wc_terms_wpml() {
global $sitepress;
$active_languages = $sitepress->get_active_languages();
$current_language = $sitepress->get_current_language();
foreach ( $active_languages as $lang ) {
$sitepress->switch_lang( $lang['code'] );
$product_cats = get_terms(
'product_cat',
[
'hide_empty' => false,
'fields' => 'id=>parent',
]
);
_wc_term_recount( $product_cats, get_taxonomy( 'product_cat' ), true, false );
$product_tags = get_terms(
'product_tag',
[
'hide_empty' => false,
'fields' => 'id=>parent',
]
);
_wc_term_recount( $product_tags, get_taxonomy( 'product_tag' ), true, false );
}
$sitepress->switch_lang( $current_language );
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question