Support » Themes and Templates » Add a class and a span to all links in articles

  • Resolved ScytheZ

    (@scythez)


    On my site: http://marketing-constructii.ro/ i want and would love to have the 3D Rolling Links css trick. The problem is that i don’t know know how to add a class to all <a> and a <span> inside of it.

    In the end to look alright it should look like this

    <a href="http://hbr.org/2009/04/how-toxic-colleagues-corrode-performance/ar/1/" class="roll" target="_blank"><span data-title="Harvard Business Review"> Harvard Business Review </span></a>

    But only inside the article .. i mean the_content loop.
    Any help is greatly appreciated. For now i can add the code manually but would love (and make sense) to be automatically coded whenever i add a link and post a new article.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Take a look in StackOverflow, many answers dealing with the same issue over there. Much probably, you’ll find a good example on how to do it with jQuery.

    Normally, one don’t even have to ask. Just search and lots of good snippets pop out.

    Thank you for the pointer.
    This one did the trick for me

    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] . ' class="roll"><span data-title="' . esc_attr( $title ) . '">' . $matches[2] . '</span></a>';
        }
    }

    from here

    Solved (for me)

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Add a class and a span to all links in articles’ is closed to new replies.