如何在不影响 alt 属性关键字的情况下将关键字替换为 link
How to replace keywords to link in Wordpress without affecting keywords in alt attribute
我试图将 post 内容中的关键字替换为链接,但是,我意识到 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');
不久前我不得不做一些类似的事情,试试这个作为你的功能 - 它可能需要一些摆弄和调整,因为我在没有测试的情况下适应你的例子
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;
}
我试图将 post 内容中的关键字替换为链接,但是,我意识到 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');
不久前我不得不做一些类似的事情,试试这个作为你的功能 - 它可能需要一些摆弄和调整,因为我在没有测试的情况下适应你的例子
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;
}