duanqujing3863 2016-05-31 15:22
浏览 13
已采纳

如何在不影响alt属性中的关键字的情况下替换要在Wordpress中链接的关键字

I was trying to replace keywords in post content to links, however, I realise the keywords in alt attribute of img tag was also affected. Is there solution for that? BTW, the code I was using in functions.php:

function replace_text_wp($text){  
$replace = array(  
    'keyword1' => '<a href="http://demo.com/" rel="bookmark" title="keyword1">keyword1</a>',  
);  
$text = str_replace(array_keys($replace), $replace, $text);  
return $text;  

}

add_filter('the_content', 'replace_text_wp');

  • 写回答

1条回答 默认 最新

  • doukanmang3687 2016-05-31 15:45
    关注

    I had to do something similar not too long ago, try this as your function - it might well need some fiddling and tweaking as I am adapting it to your example without testing

    function replace_text_wp($the_content){  
        //Break up the content into parts - allowing us to just edit content and not tags
        $parts = preg_split('/(<(?:[^"\'>]|"[^"<]*"|\'[^\'<]*\')*>)/', $the_content, -1, PREG_SPLIT_DELIM_CAPTURE);
        // Loop through the blocks and just edit the content
        for ($i=0, $n=count($parts); $i<$n; $i+=2) {
          // Check if any of our keywords are within the content
            // If so then make the keywords a link
            $parts[$i] = str_replace('keyword1', '<a href="http://demo.com/" rel="bookmark" title="keyword1">keyword1</a>', $parts[$i]);
          }
        }
        // Now put it all back together
        $the_content = implode('', $parts);
        return $the_content;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题