douxue4395
2019-03-18 13:15
浏览 41
已采纳

在产品描述WooCommerce中添加no-follow到所有外部链接

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;
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duannong1801 2019-03-18 13:56
    已采纳

    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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题