【问题标题】:How to replace keywords to link in Wordpress without affecting keywords in alt attribute如何在不影响 alt 属性中的关键字的情况下替换关键字以在 Wordpress 中链接
【发布时间】:2016-09-29 16:51:43
【问题描述】:

我试图将帖子内容中的关键字替换为链接,但是,我意识到 img 标签的 alt 属性中的关键字也受到了影响。 有解决方案吗?顺便说一句,我在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');

【问题讨论】:

    标签: php wordpress filter hook


    【解决方案1】:

    不久前我不得不做一些类似的事情,试试这个作为你的功能 - 它可能需要一些摆弄和调整,因为我正在调整它以适应你的示例而无需测试

    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;
    }
    

    【讨论】:

    • 谢谢西蒙,正则表达式只做了一点改动,效果很好
    • 能否请您将此标记为有帮助或请艾伦回答 :) - 也许添加您需要的正则表达式,因为我有兴趣看到它。
    • SO 还是新手,无法标记或投票,我使用的正则表达式很简单:code$parts = preg_split('/()/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);code 在我的情况下,我仍然希望在 标记等中有关键字被替换
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2011-10-13
    • 2021-09-18
    • 2018-09-25
    相关资源
    最近更新 更多