Wordpress,为所有链接添加<span>标记

Seb*_*röm 2 html php wordpress

当我在Wordpress网站上写博客文章时,我想在所有锚标签中动态添加span-tag,其数据属性与锚标签具有相同的值.

例

我在Wordpress中写的内容:

<p>Some text with <a href="#">a link in it</a></p>
Run Code Online (Sandbox Code Playgroud)

产生的结果:

<p>Some text with <a href="#"><span data-title="a link in it">a link in it</span></a>
Run Code Online (Sandbox Code Playgroud)

你怎么能用jQuery或PHP做到这一点?

Nik*_*lov 6

使用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>';
    }
}
Run Code Online (Sandbox Code Playgroud)

这个函数的作用是它挂钩the_content过滤并在所有锚标记内放置一个span.

请注意,如果锚包含图像,则不会添加跨度 - 如果需要,可以通过将_add_span函数更改为:来更改此行为:

function _add_span( $matches ) {
    return '<a' . $matches[1] . '><span data-title="' . esc_attr( strip_tags( $matches[2] ) ) . '">' . $matches[2] . '</span></a>';
}
Run Code Online (Sandbox Code Playgroud)

一个jQuery解决方案也不会很难,但我认为只有PHP足够了.