I'm looking for a way to hide outdated skus in WooCommerce.
The method below works. I'm wondering if I'm missing a way to accomplish this with fewer iterations.
Is it possible to exclude products from a search by an array of skus?
Can a syntax like this be made to work with skus in WooCommerce query? $query = new WP_Query( array( 'cat' => '-12,-34,-56' ) );
Is it possible to apply settings to query results without iterating through the array?
Also, I've seen two syntaxes recommended for hiding products. Which of these is least likely to be deprecated in the future?
$terms = array( 'exclude-from-search', 'exclude-from-catalog' ); // for hidden..
wp_set_post_terms( $prod_ID, $terms, 'product_visibility', false );
Change product visibility via PHP on Woocommerce 3+
Or this syntax:
// Get an instance of the product variation from a defined ID
$child_product = wc_get_product(child_id);
// Change the product visibility
$child_product->set_catalog_visibility('visible');
// Save and sync the product visibility
$child_product->save();
Update the product visibility in Woocommerce 3
This works, but I'm wondering if it's possible to get rid of either or both of the iterative processes:
function test_hide_outdated_skus(){
$product_ids_to_keep = array();
$skus_to_keep = array('sku_0','sku_1','sku_2','sku_3','sku_4');
foreach ($skus_to_keep as $p) {
if (wc_get_product_id_by_sku($p)) {
array_push($product_ids_to_keep,wc_get_product_id_by_sku($p));
}
}
$query = new WC_Product_Query(array(
'exclude' => $product_ids_to_keep,
'limit' => -1,
'tax_query' => array( array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => array('exclude-from-search', 'exclude-from-catalog' ),
'operator' => 'NOT IN'
) ),
) );
$products = $query->get_products();
foreach ($products as $prod) {
$prod->set_catalog_visibility('hidden');
$prod->save();
}
}