admin管理员组文章数量:1122832
Is there a filter I could use to get and change the html output of a link? I would need to add a target="_blank" in some cases.
I'm using the filter post_link to change the url itself where neccessary, but I would need to be able to modify the html part as well. I cannot find correct filter, I ran into a "edit_post_link" filter, but that didn't do the trick as it seems like it's working only at the back-end.
Thanks to everyone who can give me some hint!
Is there a filter I could use to get and change the html output of a link? I would need to add a target="_blank" in some cases.
I'm using the filter post_link to change the url itself where neccessary, but I would need to be able to modify the html part as well. I cannot find correct filter, I ran into a "edit_post_link" filter, but that didn't do the trick as it seems like it's working only at the back-end.
Thanks to everyone who can give me some hint!
Share Improve this question asked Aug 21, 2019 at 15:18 PavelPavel 11 bronze badge 3 |1 Answer
Reset to default 0If you use the filter "the_content" you can use a combination of preg_...
statements to loop through all links, adding target="_blank" to those matching your specific requirements. You can add this filter to your functions.php, or to select page,post, or category templates .
add_filter( 'the_content', 'ex1_the_content_filter' );
function ex1_the_content_filter($content) {
// finds all links in your content
preg_match_all('/(\<a href=.*?a>)/',$content,$matches, PREG_SET_ORDER);
// loop through all matches
foreach($matches as $m){
// potential link to be replaced...
$toReplace = $m[0];
// if current link does not already have target="{whatever}"
// You can add whatever additional "IF" you require to this one
if (!preg_match('/target\s*\=/',$toReplace)){
// adds target="_blank" to the current link
$replacement = preg_replace('/(\<a.*?)(\>)(.*?\/a\>.*?)/','$1 target="_blank"$2$3',$toReplace);
// replaces the current link with the $replacement string
$content = str_ireplace($toReplace,$replacement,$content);
}
}
return $content;
}
本文标签: How to add a target to a link
版权声明:本文标题:How to add a target to a link 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736289243a1928264.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
function pv_external_link($url, $post) { if ($post->ID > 0) { if (get_post_meta($post->ID, 'pv_url', true)) { $url = get_post_meta($post->ID, 'pv_url', true); } } return $url; } add_filter('post_link', 'pv_external_link', 10, 2);
And to those links I would need to apply also a target. – Pavel Commented Aug 22, 2019 at 7:48