Site logo

[Resolved] Making A Custom Link Class Open In A New Tab

Home Forums Support [Resolved] Making A Custom Link Class Open In A New Tab

Home Forums Support Making A Custom Link Class Open In A New Tab

Viewing 9 posts - 1 through 9 (of 9 total)
  • Author
    Posts
  • #2463761
    Jodie

    Hi,

    I have a class of links on my website which are a different color.

    Could I make that class automatically open in a new tab and be marked as “nofollow”?

    Thanks for your help!

    Cheers Jodie

    #2463765
    Fernando
    Customer Support

    Hi Jodie,

    Can you point us to a sample link that you want this attribute to be added to?

    #2463834
    Jodie

    Hi Fernando,

    Sure!

    Cheers Jodie

    #2463921
    David
    Staff
    Customer Support

    Hi there,

    try adding this PHP Snippet to the site:

    
    add_filter( 'render_block', function( $block_content, $block ) {
        if ( 
            ! empty( $block['attrs']['className'] ) 
            && 'important-link' === $block['attrs']['className']  
        ) {
            $block_content = str_replace( '<a ', '<a target="_blank" rel="nofollow" ', $block_content );
        }
    
        return $block_content;
    }, 10, 2 );
    #2464710
    Jodie

    Hi David,

    That worked perfectly, thank you so much!

    How do you add notes in PHP so I can tell what function does which?

    Thanks for your help.

    Cheers Jodie

    #2464761
    Jodie

    Hi David,

    Also, I have another Custom Class for a link I’d like to automatically open in a new tab.

    How is best to do this? Thanks for your help!

    Cheers Jodie

    #2465021
    David
    Staff
    Customer Support

    Comments in PHP – there are 2 types:

    // single line comments

    and

    
    /* 
    block of text 
    across many line
    comments 
    */

    Update code here with comments 🙂

    // links with class important-link or goodreads-link
    // open in new window and rel no follow
    add_filter( 'render_block', function( $block_content, $block ) {
        // check the block for class names
        if ( 
            ! empty( $block['attrs']['className'] ) 
            && ( 
                'important-link' === $block['attrs']['className'] 
                || 'goodreads-link' === $block['attrs']['className'] 
            )
        ) {
            $block_content = str_replace( '<a ', '<a target="_blank" rel="nofollow" ', $block_content );
        }
    
        return $block_content;
    }, 10, 2 );
    #2465614
    Jodie

    Hi Fernando,

    Thank you so much! Much appreciated as always.

    Cheers Jodie

    #2465860
    David
    Staff
    Customer Support

    Glad we could be of help

Viewing 9 posts - 1 through 9 (of 9 total)
  • You must be logged in to reply to this topic.