Frank Leaster Frank Leaster - 5 months ago 11
CSS Question

WooCommerce: Hide css propriety when an element is empty

I tried to add a custom field into the products list in the shop page of my website.
I used this code in

functions.php
file:

add_action( 'woocommerce_after_shop_loop_item_title', 'ins_woocommerce_product_excerpt', 3);

if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}

if (!function_exists('ins_woocommerce_product_excerpt'))
{
function ins_woocommerce_product_excerpt() {

global $post;
$item = get_post_meta( $post->ID, 'item12', true );

if ( $item !== "" || is_home() || is_shop() || is_product_category() || is_product_tag() ) {


echo '<span class="item12"><em>';
echo ( $item );
echo '</em></span>';

}
}
}


The code works and shows the custom field (with a green label made in css),
over the image product in the shop page.

css codes:

.item12 {
position: absolute;
margin-top: -3.750em;
z-index: 8;
color: #FFFFFF;
display: block;
color: #FFFFFF;
text-shadow: black 0.063em 0.063em 0.313em;
font-weight: 800;
font-size: 1.125em;
background-color: rgba(89, 140, 31, 0.71);
border-radius: 0.438em;
padding: 0.313em 0.313em 0.313em 0.313em;
position: absolute;
/* margin-top: -100px; */
margin-left: 9.375em;
}


The problem is when the custom field is empty, a green dot is visibile over the image.

How can I do to show the label only when the custom field is not empty?

Thanks.

Answer

Add New Code in function.php Like This

   add_action( 'woocommerce_after_shop_loop_item_title', 'ins_woocommerce_product_excerpt', 3);  

if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}

if (!function_exists('ins_woocommerce_product_excerpt'))
{
function ins_woocommerce_product_excerpt() {

global $post;
$item = get_post_meta( $post->ID, 'item12',true) ;

if ( $item !== "" || is_home() || is_shop() || is_product_category() ||        is_product_tag() ) {

if(!empty($item)){
echo '<span class="item12"><em>';
echo ( $item );
echo '</em></span>';
}
}
}
}   

add_action( 'woocommerce_after_shop_loop_item_title', 'ins_woocommerce_product_excerpt', 3);  

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

if (!function_exists('ins_woocommerce_product_excerpt'))
{
    function ins_woocommerce_product_excerpt() {

        global $post;
        $item = get_post_meta( $post->ID, 'item12', true );

        if ( $item !== "" || is_home() || is_shop() || is_product_category() || is_product_tag() ) {

            if(!empty($item)){
                echo '<span class="item12"><em>';
                echo ( $item );
                echo '</em></span>';
            }
        }
    }
}
Comments