• Resolved MiKeZZa

    (@mikezza)


    I want to achieve this: if a product is sold it must be moved to a specific category

    I’ve a custom plugin with this code:

    
    
    <?php
    /**
    * Plugin Name: ....
    * Plugin URI: ....
    * Description: ....
    * Version: 1.0
    **/
    
    add_action('woocommerce_thankyou', 'move_product', 10, 1);
    function move_product( $order_id ) {
        if ( ! $order_id )
            return;
    
    	error_log("Print 1", 0);
    	
        // dont do it twice, so check if already done for this order
        if( ! get_post_meta( $order_id, '_thankyou_action_done', true ) ) {
    
    		error_log("Print 2".$order_id, 0);
    		
            $order = wc_get_order( $order_id );
    
            // Get the order key
            $order_key = $order->get_order_key();
    
    		error_log("Print 3".$order_key, 0);
    		
            // Get the order number
            $order_key = $order->get_order_number();
    
    	//check if order is paid
            //$paid = $order->is_paid(); //true of false zijn de return waardes       
    
           
            foreach ( $order->get_items() as $item_id => $item ) {
    
    			error_log("Print 4".$item_id, 0);
    			
                // Get the product object
                $product = $item->get_product();
    
    			error_log("Print 5".$item, 0);
    			
                // Get the product Id
                $product_id = $product->get_id();
    
    			error_log("Print 6".$product_id, 0);
    			
    	    if($product->get_stock_quantity() == 0){
    		//	$product->update_meta_data('product_cat', 34);
    		wp_set_object_terms($product_id, 34, 'product_cat');
    			error_log("Print 7".$product_id, 0);
    	    }
            }
    
            // don't do it twice, so update meta data on this order
            $order->update_meta_data( '_thankyou_action_done', true );
            $order->save();
        }
    }

    `

    This works sometimes (lets say 20% of the times), but most of the products stay in the same category, so something is wrong. Error logging and so on says nothing special, so it seems that the method that is used is not valid for all sales or something. On an other, test, WooCommerce shop it seems to work fine.

    Can somebody help me with a tip or an idea?

    The error_log in it is for seeing the variables in my logging for troubleshooting.

    • This topic was modified 3 years, 8 months ago by MiKeZZa.
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Moving products to other category after order’ is closed to new replies.