How can I selectively show out of stock products in a category view? I know I can do it in the WooCommerce options panel for all products but I need to control this more. I'm thinking along the lines of adding something into the functions.php of my theme such as:
add_action( 'xyz', function() {
global $product;
if ( !$product->is_in_stock() ) {
//Need to make it viewable here but selectively, not globally;
}
});
A single checkbox toggle on the product page would be perfect, eg "Show even if stock level is zero".
Note - With > 500 products, I need to have a checkbox for those few that I need visible, not the other way round.
Any ideas?
Well that was a heck of a lot trickier than I thought it was going to be. The solution comes in three parts.
First, you must add a checkbox to the admin product metabox. I thought it would be appropriate if we placed it near the stock status inputs.
add_action( 'woocommerce_product_options_stock_status', 'so_27971630_hide_if_out_of_stock' );
function so_27971630_hide_if_out_of_stock(){
woocommerce_wp_checkbox( array( 'id' => '_hide_if_out_of_stock', 'wrapper_class' => 'show_if_simple show_if_variable', 'label' => __( 'Hide this product from archives when out of stock?', 'your-plugin-domain' ) ) );
}
Then we need to save this data. Normally, I'd save a checkbox as 'yes' versus 'no' like WooCommerce does. However, getting the product query correct, required that the meta exist when you wanted to hide the item and not exist at all otherwise... hence the if/else update_post_meta() versus delete_post_meta()
add_action( 'woocommerce_process_product_meta', 'so_27971630_save_product_meta' );
function so_27971630_save_product_meta( $post_id ){
if( isset( $_POST['_hide_if_out_of_stock'] ) ) {
update_post_meta( $post_id, '_hide_if_out_of_stock', 'yes' );
} else {
delete_post_meta( $post_id, '_hide_if_out_of_stock' );
}
}
Finally, we need to tweak the product query. WooCommerce builds a custom query for products in its WC_Query class. Basically what I've done is in the case where you aren't mass hiding all out of stock items via the plugin option, this code will modify the meta query so that any item that does not have the meta key _hide_if_out_of_stock will be shown. That is a counter-intuitive way of sayingn that any product where the box "hide when out of stock" is checked will be hidden.
add_action( 'woocommerce_product_query', 'so_27971630_product_query' );
function so_27971630_product_query( $q ){
$meta_query = $q->get( 'meta_query' );
if ( get_option( 'woocommerce_hide_out_of_stock_items' ) == 'no' ) {
$meta_query[] = array(
'key' => '_hide_if_out_of_stock',
'compare' => 'NOT EXISTS'
);
}
$q->set( 'meta_query', $meta_query );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With