-
-
Save INDIAN2020/141175970a35780f272f4687bf6f1807 to your computer and use it in GitHub Desktop.
Unpublish a product in #woocommerce when it's sold out
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| * Unpublish products after purchase | |
| */ | |
| add_action( 'woocommerce_thankyou', 'yanco_unpublish_product_if_sold_out', 10, 1 ); | |
| function yanco_unpublish_product_if_sold_out( $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'] ); | |
| if( get_post_meta( $product['product_id'], '_manage_stock' ) == 'yes' ) { | |
| // This will only work if stock management has been enabled | |
| $product_stock_quantity = $product_object->get_stock_quantity(); | |
| if( $product_stock_quantity == 0) { | |
| wp_update_post( | |
| array( | |
| 'ID' => $product['product_id'], | |
| 'post_status' => 'draft' | |
| ) | |
| ); | |
| } | |
| else if ( $product_stock_quantity < 1 ) { | |
| wp_update_post( | |
| array( | |
| 'ID' => $product['product_id'], | |
| 'post_status' => 'draft' | |
| ) | |
| ); | |
| } | |
| elseif ( $product_stock_quantity == null ) { | |
| wp_update_post( | |
| array( | |
| 'ID' => $product['product_id'], | |
| 'post_status' => 'draft' | |
| ) | |
| ); | |
| } else { | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment