Skip to content

Instantly share code, notes, and snippets.

@INDIAN2020
Forked from yanknudtskov/functions.php
Created June 18, 2018 06:11
Show Gist options
  • Save INDIAN2020/141175970a35780f272f4687bf6f1807 to your computer and use it in GitHub Desktop.
Save INDIAN2020/141175970a35780f272f4687bf6f1807 to your computer and use it in GitHub Desktop.
Unpublish a product in #woocommerce when it's sold out
<?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