gpt4 book ai didi

html - 如何在 Post 中的链接标记内添加 HTML 标记和类 - Wordpress

转载 作者:行者123 更新时间:2023-11-27 23:55:15 25 4
gpt4 key购买 nike

我想在 Post 的链接标签内添加类和 html 标签,所以我将一个词链接到我的 wordpress 页面之一,如下所示:

<a href="http://localhost/website/contact/">contact</a>

我希望当我链接它时:

<a href="http://localhost/website/contact/" class="class1 class2"><span>contact</span></a>

因为我的主题使用 span 来实现悬停功能。

如果可能只在帖子(博客部分)中,有一个所有帖子都有的类:post-contents

我知道我可以修改帖子的 HTML 代码,但我希望它是通用的,所以只要我在帖子中添加链接(甚至是新链接),就会添加类和 span 标签

有什么想法吗?

最佳答案

这应该可以解决问题;

function wrap_anchor_text_with_span( $content ) {
if ( ! is_admin() && preg_match( '~<a(.*?)>(.*?)</a>~', $content ) ) {
$content = preg_replace_callback( '~<a(.*?)>(.*?)</a>~', '_add_span', $content );
}
return $content;
}
add_filter('the_content', 'wrap_anchor_text_with_span', 10);

function _add_span( $matches ) {
if ( ! ( $title = strip_tags( $matches[2] ) ) ) { // If we only have an image inside the anchor
return '<a' . $matches[1] . '>' . $matches[2] . '</a>';
} else {
return '<a' . $matches[1] . '><span data-title="' . esc_attr( $title ) . '">' . $matches[2] . '</span></a>';
}
}

What this function does is that it hooks to the_content filter and places a span inside all anchor tags.

请注意,如果 anchor 包含图像,则不会添加跨度。根据另一个线程的另一个答案,Nikola Ivanov Nikolov

然后使用过滤器来处理 anchor ...

add_filter('the_content', 'addClassToLinks');
function addClassToLinks($content){
return str_replace( '<a ', "<a class='myclass'", $content);
}

希望这对您有所帮助。

问候,-B.

关于html - 如何在 Post 中的链接标记内添加 HTML 标记和类 - Wordpress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56300812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com