phpwordpresswoocommerceproductnofollow

Adding no-follow to all external links in product-description WooCommerce


A website has 300 products and all with do-follow. I need to make them all no-follow and future links as well, but only if the links are inside the productloop.

This code generates for the entire site. How Would I do it specifically to the woocommerce product?

add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');

function my_nofollow($content) {
    return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
}

function my_nofollow_callback($matches) {
    $link = $matches[0];
    $site_link = get_bloginfo('url');

    if (strpos($link, 'rel') === false) {
        $link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link);
    } elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
        $link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link);
    }
    return $link;
}

Solution

  • Update 2: Try the following (untested) restricting to Woocommerce single product pages only:

    add_filter('the_content', 'my_nofollow', 10, 1 );
    add_filter('woocommerce_short_description', 'my_nofollow', 10, 1 );
    
    function my_nofollow( $content ) {
        if( is_product() ) 
            return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
        else
            return $content;
    }
    
    function my_nofollow_callback($matches) {
        $link = $matches[0];
        $site_link = get_bloginfo('url');
    
        if (strpos($link, 'rel') === false) {
            $link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link);
        } elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
            $link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link);
        }
        return $link;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    Related : Woocommerce conditional tags official documentation