Programmatically add and remove woocommerce product category
I have an existing product category in woocommerce called ‘whats-new’, with an ID of 35.
I want to progmatically add all (existing and new) products less than 30 days old to that category, without going through and ticking them all.
Then any products that go over the 30 days, automatically remove that category.
I feel like there must be a way to do this in WordPress, but it’s proving pretty difficult for some reason and I’m going round in circles a little.
I have the following code, which is basically what I want to achieve. The time function works, but adding and remove thing category does not:
$product = wc_get_product($id);
global $product;
$datetime_created = $product->get_date_created();
$timestamp_created = $datetime_created->getTimestamp();
$datetime_now = new WC_DateTime();
$timestamp_now = $datetime_now->getTimestamp();
$time_delta = $timestamp_now - $timestamp_created;
$sixty_days = 60 * 24 * 60 * 60;
$cat_ids = array( 35 );
if ( $time_delta < $sixty_days ) {
// NEW PRODUCT - add 'whats-new' category
wp_set_object_terms( $product_id, $cat_ids, 'product_cat', true );
} elseif ( $time_delta > $sixty_days ) {
// OLD PRODUCT - remove 'whats-new' category
wp_remove_object_terms( $product_id, $cat_ids, 'product_cat', true );
}
Leave an answer
You must login or register to add a new answer .