P
P
Pavel2020-05-13 11:37:40
WordPress
Pavel, 2020-05-13 11:37:40

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:
5ebbb0b49b82e376689151.png
5ebbb0aaef536566238237.png
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 );
}


The hook works, even get_term() selects the necessary categories according to the language, but for some reason the recalculation has no effect. If I just call my recount_wc_terms_wpml function, for example just from header.php, then everything works fine. But why doesn't _wc_term_recount work inside a hook?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question