I have the following snippet to check if an item is out of stock and if so to change its status to draft from published. How can I exlude one category in this query? Thank you!
add_action('admin_init', 'woo_moveoutofstocktodraft');
function woo_moveoutofstocktodraft() {
$current_user = wp_get_current_user();
//if loggedin user does not have admin previlage
if (!user_can($current_user, 'administrator')) {
return;
}
$params = [
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish'
];
$wc_query = new WP_Query($params);
if ($wc_query->have_posts()) :
while ($wc_query->have_posts()) :
$wc_query->the_post();
$product_id = get_the_ID();
$product = wc_get_product($product_id);
//if product is Out of Stock move to draft
if (!$product->is_in_stock()) {
$post = array( 'ID' => $product_id, 'post_status' => 'draft' );
wp_update_post($post);
}
endwhile;
wp_reset_postdata();
endif;
}
2
Answers
use tax_query parameter in your query arg,
e.i.
But I’d say this uses way too much resources and doing a lot of useless overhead just for doing a simple thing.
your code performs the following;
you better of doing ONE raw sql UPDATE statement that joins the meta and taxonomy related table, would probably use 99% less resource than your current approach
I have modified your code and in this modified code:
Replace 123 with the actual ID of the category you want to exclude.
The tax query parameter is added to the $params array to exclude products from the specified category.
The operator ‘NOT IN’ is used to exclude products from the specified category.