Snippets

Pavel Petrov How to add tags on WooCommerce products

Created by Pavel Petrov
1
2
3
4
<div class="flagcontainer">
    <span class="flag discount">-20%</span>
    <span class="flag free-shipping">Free shipping</span>
</div>
<?php
//...
add_action( 'woocommerce_before_shop_loop_item_title', function() {
    echo woocommerce_get_product_thumbnail();
	global $product;
	echo '<div class="flagcontainer">';
	//1.Show discount percentage in a tag
	if( $product->is_on_sale() )
	{	
		if( $product->is_on_sale() )
		{
			$available_variations = $product->get_available_variations();								
			$maximumper = 0;
			for ($i = 0; $i < count($available_variations); ++$i) {
				$variation_id=$available_variations[$i]['variation_id'];
				$variable_product1= new WC_Product_Variation( $variation_id );
				$regular_price = $variable_product1 ->regular_price;
				$sales_price = $variable_product1 ->sale_price;
				$percentage= round((( ( $regular_price - $sales_price ) / $regular_price ) * 100),1) ;
				if ($percentage > $maximumper) {
					$maximumper = $percentage;
				}
			}
			echo '<span class="flag discount">'.sprintf( __('%s', 'woocommerce' ), '-'.round($maximumper) . '%' ).'</span>';	
		}
	}
	//2.If price is > 499
	if((int)$product->price >= 499)
	{
		echo '<span class="flag free-shipping">Fri frakt</span>';	
	}
	//3.If there are tags
	$terms = get_the_terms( get_the_ID(), 'product_tag' );
	$term_array = array();
	if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
		foreach ( $terms as $term ){
			echo '<span class="flag new">'.$term->name.'</span>';
		}
	}
	echo '</div>';
}, 10 );
.flagcontainer {
    position: absolute;
    top: -5px;
    left: -5px;
    line-height: 26px;
    /**/
    display:block;
}

.flag {
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;
    width: auto;
    padding: 2px 10px;
    text-align: center;
    color: #fff;
    font-size: 12px;
    font-weight: 600;
    z-index: 1;
    text-shadow: 1px 1px 1px rgba(0,0,0,.2);
    /**/
    display:block;
    margin-bottom:10px;
    margin-top: 10px;
}

.flag.new {
    background-color: #ca5410
}

.flag.free-shipping {
    background-color: #10caa9
}

.flag.discount {
    background-color: #d60a2c
}

.price > ins span {
    color: #d60a2c!important;
}
@media(min-width: 1200px) {
    .flag {
        font-size:14px
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.