Search code examples
phpwordpresswoocommerceproducttaxonomy-terms

Remove specific WooCommerce categories from single product meta section


Every solution I have found essentially unassigns a category from a product. This is not what I want. I am using product categories to provide functionality to other plugins. In my case, products with the category "preorder" have a deposit applied using a YITH plugin, products with the category "fitting" have an extra checkbox for a customer to advise if they want a quote for product fitting services.

What I am trying to achieve is to remove specific displayed category terms from the single product page on the "meta" section. Customers don't need to know that categories like "preorder" and "fitting" are there, and I don't want them to be able to select the hyperlink to view the category page. Yes, I am aware the page will still be available, but there is minimal risk there.

The HTML output on the website looks like this:

<div class="product_meta">
    <span class="sku_wrapper">SKU: <span class="sku">...</span></span>
    <span class="posted_in">
            Categories: 
            <a href="URL" rel="tag">Fitting</a>
            , 
            <a URL" rel="tag">Category 1</a>
            , 
            <a href="URL" rel="tag">Category 2</a>
            , 
            <a href="URL" rel="tag">Preorder</a>            
    </span>
</div>

Is there a way to do this using PHP?

If not, I have also been playing around with a jQuery solution, but am also struggling as I have been unable to select the preceding comma which is outside the a tag but is within the parent span.

All code I write ends up looking like this on the frontend: Categories: , Category 1,,Category 2, where the commas are not removed.

Any help is appreciated!


Solution

  • The following code will remove specific defined product category terms displayed in single product meta section:

    add_filter( 'get_the_terms', 'filter_specific_product_categories', 10, 3 );
    function filter_specific_product_categories( $terms, $post_id, $taxonomy ) {
        global $woocommerce_loop;
        
        if ( $taxonomy === 'product_cat'
        && isset($woocommerce_loop['name'])  && empty($woocommerce_loop['name']) 
        && isset($woocommerce_loop['total']) && $woocommerce_loop['total'] == 0 
        && isset($woocommerce_loop['loop'])  && $woocommerce_loop['loop'] == 1 ) {
            // Here below define your product category term(s) slug(s) in the array
            $targeted_slugs = array('preorder', 'fitting');
    
            // Loop through the terms
            foreach ( $terms as $key => $term ) {
                if ( in_array( $term->slug, $targeted_slugs ) ) {
                    unset($terms[$key]); // Remove WP_Term object
                }
            }
        }
        return $terms;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.