Home » WordPress » How to unpublish a post,page or wooCommerce product if some condition is met.

How to unpublish a post,page or wooCommerce product if some condition is met.

Using wp_update_post you can update WordPress Posts/Pages  during the process

$product_data = array(
'ID' => $product_id,
'post_status' => 'draft',
);
wp_update_post( $product_data );
Processing $wp_error


$product_data = array(
'ID' => $product_id,
'post_status' => 'draft',
);
wp_update_post( $product_data );
Processing $wp_error

Here I have updated the wooCommerce Product status to ‘draft’ when custom field date is older than current date.


function unpublishExpiredProducts() {
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
);
$products = get_posts( $args );
foreach ( $products as $product ) {
$product_id = $product->ID;
$productExpiredDate = new DateTime(get_field('product_expired_date', $product_id));
$currentDateTime = new DateTime();
$today = date_format($currentDateTime, 'Y-m-d H:i:s e');
$endDate = date_format($productExpiredDate , 'Y-m-d H:i:s e');
if($endDate < $today ) { $product_data = array( 'ID' => $product_id,
'post_status' => 'draft',
);
wp_update_post( $product_data );
}
}
}

add_action( 'init', 'unpublishExpiredProducts' );

References

Duminda Wijerathna

An all round web designer building websites Over 18 years. Interested in achieving a suitable placement in the field of IT in a growth oriented organization which offers diverse job responsibilities in order to utilize and improve my skills, Knowledge and experience.

Leave a Comment

Your email address will not be published. Required fields are marked *