Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thelonelycats/97ad9afd47bb048ddfbca4952ec91e18 to your computer and use it in GitHub Desktop.
Save thelonelycats/97ad9afd47bb048ddfbca4952ec91e18 to your computer and use it in GitHub Desktop.
functions
<?php
/* layered navigation hide out of stock items
** Función para comprobar si los productos listados, con el filtro pa_size tienen stock para la variación indicada
*/
function product_in_stock($post, $product) {
if ($_GET['filtering'] == 1 && $_GET['filter_size'] > 0 ) {
$STOCK = FALSE;
$slugmap = array();
$attribs = $product->get_variation_attributes();
$terms = get_terms( sanitize_title( 'pa_size' ));
if($terms)foreach($terms as $term)$slugmap[$term->slug]=$term->term_id;
$available = $product->get_available_variations();
if($available)foreach($available as $instockitem){
if(isset($instockitem["attributes"]["attribute_pa_size"])){
if($instockitem["attributes"]["attribute_pa_size"] == $_GET["filter_size"] && $instockitem["max_qty"]>0){
$STOCK = TRUE;
}
}
}
return $STOCK;
} else {
return true;
}
}
// Funciones para crear un div in/out of stock alrededor del producto
function check_if_out_of_stock(){
global $post,$product;
$stock = product_in_stock($post,$product);
$output = '<div class="';
$output .= $stock?"instock":"outofstock";
$output .= '">';
$output .= $stock?"": "<span class='out-stock'>" . __( 'There is no stock for selected size', 'woocommerce' ). "</span>";
echo $output;
}
add_action( 'woocommerce_before_shop_loop_item', 'check_if_out_of_stock');
function close_out_of_stock(){
echo "</div>";
}
add_action( 'woocommerce_after_shop_loop_item', 'close_out_of_stock');
Copy link

ghost commented Feb 15, 2017

Hi, thanks for this, it helped a lot.

Only changes I made was to drop close_out_of_stock() function and woocommerce_after_shop_loop_item hook and to output the class to <li <?php post_class() ?>> element, inside content-product.php, like this:

function check_if_out_of_stock( $classes ){
    global $post, $product;
    $stock = product_in_stock( $post, $product );    
    $classes[] = $stock?"filter-instock":"filter-outofstock";
    return $classes;
}
add_filter( 'post_class', 'check_if_out_of_stock' ); 

This way I was able to hide a product completely instead of just hiding inner content.
For future reference my WC version is 2.6.14.

Cheers.

@Cfomodz
Copy link

Cfomodz commented Aug 24, 2018

Does this still work?

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