当我在 WordPress 网站上撰写博客文章时,我想在所有锚标记内动态添加一个 span 标记,其数据属性与锚标记具有相同的值。
Example
我在 WordPress 中写的内容:
<p>Some text with <a href="#">a link in it</a></p>
什么生成:
<p>Some text with <a href="#"><span data-title="a link in it">a link in it</span></a>
如何使用 jQuery 或 PHP 做到这一点?
使用 PHP,您应该能够这样做:
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>';
}
}
这个函数的作用是它挂钩the_content
过滤并在所有锚标记内放置一个跨度。
Note如果锚点包含图像,则不会添加跨度 - 如果需要,您可以通过更改来更改此行为_add_span
函数:
function _add_span( $matches ) {
return '<a' . $matches[1] . '><span data-title="' . esc_attr( strip_tags( $matches[2] ) ) . '">' . $matches[2] . '</span></a>';
}
jQuery 解决方案也不会很困难,但我认为仅 PHP 就足够了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)