首页 文章

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

提问于
浏览
2

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

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做到这一点?

2 回答

  • 6

    jQuery和wrapInner()也有效:

    <p>Some text with <a class="generate_span" href="#">a link in it</a></p>
    
    <script>
    $('.generate_span').each(function(){
        $(this).wrapInner('<span data-title="'+($(this).attr('href'))+'"></span>');
    });
    </script>
    

    http://jsfiddle.net/242b8/

  • 1

    使用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 过滤器并在所有锚标记内放置一个span .

    Note 如果锚包含图像,则不会添加 Span - 如果需要,可以通过将 _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足够了 .

相关问题