Skip to content

Instantly share code, notes, and snippets.

@edmundcwm
Last active August 3, 2018 15:56
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 edmundcwm/17f7f3151ea16d367fa8c5621d668aed to your computer and use it in GitHub Desktop.
Save edmundcwm/17f7f3151ea16d367fa8c5621d668aed to your computer and use it in GitHub Desktop.
Woocommerce: Display custom labels for products in selected categories (e.g., "New In", "Flash Sale")
<?php
/**
* Display custom labels for products in selected categories
*
* @param array $labels Array labels
*
* - Instructions -
* 1) Create a product category 'Flash Sale'
* 2) Assign products to that category
*
* If you want a label for other categories,
* change the first argument of the 'has_term' function
* to the name of the category you want.
* Duplicate the entire 'if' statement and change the argument accordingly
* to insert more labels
*/
function edm_render_custom_labels( $labels ) {
//if there are no labels, exit function
if ( !count( $labels ) ) {
return;
}
?>
<div class="custom-labels">
<ul>
<?php foreach( $labels as $label ) { ?>
<li class="custom-label <?php echo $label['class'];?> "><?php echo $label['name']; ?></li>
<?php } ?>
</ul>
</div>
<?php
}
function edm_add_custom_labels() {
global $product;
//create an array to store labels
$labels = array();
//get stock status
$status = get_post_meta($product->get_id(), '_stock_status', true);
//'Flash Sale' Label. Check if product is in a category with the slug name 'flash-sale'
if ( has_term('Flash Sale', 'product_cat') ) {
$labels['sale'] = array(
'name' => 'Flash Sale',
'class' => 'flash-sale',
);
}
//New In label. Check if product is in a category with the slug name 'new-in'
if ( has_term('new-in', 'product_cat') ) {
$labels['new'] = array(
'name' => 'New In',
'class' => 'new-in',
);
}
//Out of stock label
if ( $status === 'outofstock' ) {
$labels['soldout'] = array(
'name' => 'Sold Out',
'class' => 'sold-out'
);
}
//Display labels
edm_render_custom_labels( $labels );
}
add_action( 'woocommerce_shop_loop_item_title', 'edm_add_custom_labels', 5 );
add_action( 'woocommerce_single_product_summary', 'edm_add_custom_labels' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment