0

I'm trying to show/hide two lines of text depending on whether a WooCommerce category is empty or has any products in it. Those lines are inserted in text blocks using Elementor and I've assigned a CSS #ID to each one, so I can control it.

Now, in a custom functions plugin I have, I want to add a function to control what phrase to hide using a css rule of the type: display:none;. The code I have now is:

function show_outlet_msg($content){
    $term = get_term( 40, 'product_cat' );
    $total_products=$term->count;
    if ($total_products>0){
        //Have a products 
    } else {
        //No products
    }
}

add_filter('astra_entry_content_before','show_outlet_msg');

Now I would like to apply that if there are products in Outlet, the text that there are no products in Outlet should be hidden:

#txt_outlet_zero{
display: none;
}

And in case there are no products, hide the one that says there are:

#txt_outlet_head{
display: none;
}

How can I apply these CSS rules from the php code?

2 Answers 2

0

I'm not sure if you can add styles in filters. I tested the below code in wp_head action and worked perfectly:

function show_outlet_msg(){
    $term = get_term( 40, 'product_cat' );
    $total_products=$term->count;
    if ($total_products>0){
        $html = '<style> #txt_outlet_zero{ display: none; } </style>';
    } else {
        $html = '<style> #txt_outlet_head{ display: none; } </style>';
    }
    echo $html;
}

add_action('wp_head','show_outlet_msg');
1
0

You can hook to wp_enqueue_scripts and use wp_add_inline_style():

add_action( 'wp_enqueue_scripts', 'wpse383179_inline_style' );
function wpse383179_inline_style() {
    $term = get_term( 40, 'product_cat' );
    $total_products=$term->count;
    if ($total_products>0){
        $css = '#txt_outlet_zero { display: none; }';
    } else {
        $css = '#txt_outlet_head { display: none; }';
    }
    wp_add_inline_style( '{your-css-id}', $css );
}

The tricky part is determining what your-css-id should be. You can view the source of a given page and check the <link rel="stylesheet" ...> tags. The CSS ID for each of them (assuming they've been properly registered and enqueued for WordPress) will be in the id attribute, with -css appended to it. So, if you see, eg,

<link rel="stylesheet" id="my-styles-css" src="/path/to/stylesheet.css" />

... then the {your-css-id} bit in my code snippet should be my-styles.

However

That said, is there a reason to generate two different CSS IDs for this? There's never going to be a situation where the $total_products is 0 and greater than 0. There may be an easier way, eg, adding a single <div> and changing the content inside it based on the product count.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.