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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)