简体   繁体   中英

How do I automatically set WooCommerce Product to draft if sold out

I tried using the 'Hide if sold out' option in Woocommerce. But I am using a different plugin to display my products (GridFX Masonry Gallery) and it is still showing the sold out products. Is there a way to change the product to draft when the last item has been purchased and is sold out? Is there a snippet to do this?

The previous answer by Maha Dev cannot work.

In a theme functions file the get_stock_quantity() method doesn't exist unless you call the product data using wc_get_product .

Using set_post_type will change the actual type of the post, not it's status, you need to use wp_update_post and set the post status.

This is the code I ended up using:

/*
* Unpublish products after purchase
*/
function lbb_unpublish_prod($order_id) {

    $order = new WC_Order( $order_id );

    $all_products = $order->get_items();
    foreach ($all_products as $product){
        $product_object = wc_get_product($product['product_id']);
            // This will only work if stock management has been enabled
        if( ! $product_object->get_stock_quantity() ) {
            wp_update_post(array(
                'ID' => $product['product_id'],
                'post_status' => 'draft'
                ));
        }

    }
}
add_action( 'woocommerce_thankyou', 'lbb_unpublish_prod', 10, 1 );

Better way is to set product stock (1 in your case). Select 'Hide out of stock products'. It will hide out of stock products. But if you actually want to hide ordered products then see my code below:

//functions.php    

add_action( 'woocommerce_thankyou', 'your_func', 10, 1 );

    function your_func($order_id) {

        $order = new WC_Order( $order_id );

        $all_products = $order->get_items();
        foreach ($all_products as $product){
            // This will only work if stock management has been enabled
            if( ! $product->get_stock_quantity() )
                set_post_type ($product['product_id'], 'draft');
        }
    }

This will hide all the products added in the cart for order. You can customize this function as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM