Wordpress 用链接替换内容中的标记词 [英] Wordpress Replace Tag Words in Content with Links

查看:26
本文介绍了Wordpress 用链接替换内容中的标记词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码片段,用链接替换了 the_content() 中的特定词:

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

我想使用 get_the_tags() 作为 $replace 数组,以便它用指向标签存档的链接替换特定的标签词.

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

推荐答案

这是完整的解决方案.

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

请注意,我没有使用 get_the_tags 函数,因为它只返回分配给帖子的标签,所以我使用了 get_tags 函数

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

这篇关于Wordpress 用链接替换内容中的标记词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆