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

在产品描述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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容