Skip to content

Instantly share code, notes, and snippets.

@jartes
Last active September 6, 2016 15:24
Show Gist options
  • Save jartes/9622936 to your computer and use it in GitHub Desktop.
Save jartes/9622936 to your computer and use it in GitHub Desktop.
WooCommerce - Is out of stock category

WooCommerce - Is out of stock category

Overview

This function checks if all products belonging to a product category or custom taxonomy is out of stock.

This function uses Transients API to cache 1 hour the result for avoiding large amount of querys.

Usage

<?php wc_check_is_out_stock_category( $term_id, $taxonomy ) ?>

Parameters

$term_id
(string) (required) Category id or term id to check
Default: false

$taxonomy
(string) (optional) Category id or term id to check
Default: 'product_cat' (WooCommerce Product Category)

Return Values

(boolean) True on success, false on failure.

<?php
function wc_check_is_out_stock_category( $term_id = false, $taxonomy = 'product_cat' ) {
if ( $term_id === false )
return false;
// Check if we have in cache the value
$cached_cat = get_transient( 'wc_out_stock_' . $taxonomy . '_' . $term_id );
if ( $cached_cat === false ) {
// We don't have it in cache, so let's get it and cache it!
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $term_id
),
),
);
$cat_prods = get_posts( $args );
foreach ( $cat_prods as $single_prod ) {
$product = get_product( $single_prod->ID );
if ( $product->is_in_stock() === true ) {
// At least one product is in stock, so this category is in stock
$is_out = "0";
// Store transient into de DB and give him 1 hour of life.
set_transient( 'wc_out_stock_' . $taxonomy . '_' . $term_id, $is_out, 1 * HOUR_IN_SECONDS );
// Exit
return false;
}
}
// All products are in stock so this category is out ouf stock
$is_out = "1";
set_transient( 'wc_out_stock_' . $taxonomy . '_' . $term_id, $is_out, 1 * HOUR_IN_SECONDS );
// Exit
return true;
}
else {
if ( $cached_cat == "1" ) {
return true;
}
elseif ( $cached_cat == "0" ) {
return false;
}
}
}
?>
@OGSWEB
Copy link

OGSWEB commented Mar 3, 2015

Hi Jartes!
I don't know if I can ask for your help ...
I'm trying to have a list of products brands containing in stock products (product_brand instead of product_cat)
Can I use your code? I yes, how can I implement it?
Thank you and best regards :-)

'title', 'order' => 'ASC', 'hide_empty' => '1', ``` ); $product_categories = get_terms( 'product_brand', $args ); $count = count($product_categories); if ( $count > 0 ){ foreach ( $product_categories as $product_category ) { ``` echo '' . $product_category->name . '
'; } ``` } ?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment