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 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致
  • ¥15 在使用pyecharts时出现问题
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算