Site logo

Archived topic

Making A Custom Link Class Open In A New Tab

8 replies · Started by Jodie on December 16, 2022

Viewing posts 1–9 of 9

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

Hi Jodie,

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

Hi Fernando,

Sure!

Cheers Jodie

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 );

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

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

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 );

Hi Fernando,

Thank you so much! Much appreciated as always.

Cheers Jodie

Glad we could be of help

This archived topic is closed to new replies.