Accueil 2026 Forums How to WooCommerce WooCommerce – Changer de catégorie quand produit acheté



Capture d'écran 2025 11 19 221154

Étiqueté : 

2 sujets de 1 à 2 (sur un total de 2)
  • Auteur
    Messages
  • #500446
    Laure Valery
    Participant
    Points: 12 pts

    Bonjour,

     

    Je souhaite que lorsqu’un de mes produits est acheté, il change de catégorie (passe de en stock à résultats).

    Voici mon code actuel :

    add_action(‘woocommerce_order_status_changed’, ‘add_category_to_order_items_on_completed_status’ ,10, 1);

    function add_category_to_order_items_on_completed_status( $order_id ) {

    // la catégorie dans laquelle on achète

    $your_category = ‘en-stock’;

    // on récupère chaque commande

    $order = wc_get_order( $order_id );

    // si le statut de la commande est « complète »

    if ( $order->has_status( ‘completed’ ) ) {

     

    // pour chaque produit acheté

    foreach ( $order->get_items() as $item_id => $product_item ) {

    $product_id = $product_item->get_product_id();

     

    // mettre le produit dans la catégorie résultats

    wp_set_object_terms( $product_id, $your_category, ‘resultats’ );

    }    }}

    ...
    #545581
    bari
    Participant
    Points: 15 pts

    It looks like the logic is almost there, but wp_set_object_terms() is being used incorrectly. The second parameter should be the category slug you want to assign, and the third parameter should always be ‘product_cat’ for WooCommerce product categories — not the name of your target category.

    Also, if you want to move the product from one category to another, you need to remove the old category and assign the new one, not pass the old category into the function.

     

    Here’s a corrected version:

    add_action(‘woocommerce_order_status_changed’, ‘move_product_to_results_on_completed’, 10, 4);

    function move_product_to_results_on_completed($order_id, $old_status, $new_status, $order){

        if( $new_status !== ‘completed’ ) return;

        // category slugs

        $old_category = ‘in-stock’;

        $new_category = ‘results’;

        foreach ($order->get_items() as $item) {

            $product_id = $item->get_product_id();

            // Remove old category and assign new one

            wp_remove_object_terms($product_id, $old_category, ‘product_cat’);

            wp_set_object_terms($product_id, $new_category, ‘product_cat’, true);

        }

    }

     

    Enthusiastic canine advocate and proud pet parent

    ...
2 sujets de 1 à 2 (sur un total de 2)
  • Vous devez être connecté pour répondre à ce sujet.


Capture d'écran 2025 11 19 221154