Sativa Diva Sativa Diva - 5 months ago 17
PHP Question

Wordpress Replace Tag Words in Content with Links

I've got this code snippet that replaces specific words in the_content() with links:

function link_words( $text ) {

$replace = array(
'google' => '<a href="http://www.google.com">google</a>',
'computer' => '<a href="http://www.computer.com">computer</a>',
'keyboard' => '<a href="http://www.keyboard.com">keyboard</a>'
);

$text = str_replace( array_keys($replace), $replace, $text );
return $text;
}

add_filter( 'the_content', 'link_words' );


I want to use get_the_tags() as the $replace array so it replaces specific tag words with links to their tag archive.

Answer Source

Here's the complete solution.

function link_words( $text ) {

    $replace = array();
    $tags = get_tags();

    if ( $tags ) {
        foreach ( $tags as $tag ) {
            $replace[ $tag->name ] = sprintf( '<a href="%s">%s</a>', esc_url( get_term_link( $tag ) ), esc_html( $tag->name ) );
        }
    }

    $text = str_replace( array_keys($replace), $replace, $text );
    return $text;
}
add_filter( 'the_content', 'link_words' );

Please note i have not used get_the_tags function because it only returns tags assigned to the post so instead i used the function get_tags