Force meta data on specific product type

I'm working on a Woocommerce website were I have multiple product types: simple_product, enviso_group_offer and enviso_group_ticket. All of these types are just products in my Woocommerce.

No I want to add the noindex, nofollow meta tag to only the enviso_group_ticket products.

meta name=”robots” content=”noindex,nofollow”/

How can I achieve that? When I'm using the SEO plugin Yoast, I can only target all the Products, instead of a specific product type.

At this moment, I've done it with the following code, but I feels not the right way to do so:

$product_type = get_the_terms( $product_id,'product_type')[0]-slug;

if($product_type == enviso_group_ticket) {
?
    script
        jQuery(function ($) {
            $('head').append('meta name=”robots” content=”noindex,nofollow”/');
        })
    /script
?php
}

Can this be done with a Wordpress hook? Or should it be done differently? I know that I can achieve it by adding the noindex and nofollow on every enviso_group_ticket manually, but I want to force it automatically.

Thanks.

Topic woocommerce-offtopic nofollow noindex seo Wordpress

Category Web


You can try the wp_head hook:

add_action( 'wp_head', 'check_for_enviso_group_ticket' );
function check_for_enviso_group_ticket() {
    if ( is_product() && ( 'enviso_group_ticket' == get_the_terms( get_the_ID(), 'product_type' )[0]->slug ) ) {
        echo '<meta name="robots" content="noindex,nofollow"/>', PHP_EOL;
    }
}

or to not break your site in case the WooCommerce is disabled and the is_product() function isn't defined:

add_action( 'wp_head', 'check_for_enviso_group_ticket' );
function check_for_enviso_group_ticket() {
    if ( is_singular( array( 'product' ) ) && ( 'enviso_group_ticket' == get_the_terms( get_the_ID(), 'product_type' )[0]->slug ) ) {
        echo '<meta name="robots" content="noindex,nofollow"/>', PHP_EOL;
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.