WordPress, add a <span> tag to all links

When I write a blog post on my WordPress site, I want do dynamically add a span-tag inside all the anchor tags, with a data-attribute that has the same value as the anchor tag.

Example

Read More

What I write in WordPress:

<p>Some text with <a href="#">a link in it</a></p>

What generates:

<p>Some text with <a href="#"><span data-title="a link in it">a link in it</span></a>

How can you do this with jQuery or PHP?

Related posts

Leave a Reply

2 comments

  1. With PHP, you should be able to do it like that:

    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.

    Note that if the anchor contains an image, a span won’t be added – if you want, you can change this behaviour by changing the _add_span function to:

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

    A jQuery solution won’t be really difficult either, but I think that the PHP only is sufficient enough.

  2. jQuery and wrapInner() works also:

    <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/