2017-05-12 110 views
0

我有了这个代码片段,在the_content(取代具体词)WordPress的与链接内容的链接替换标签字

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()$替换数组,因此它会用指向其标记归档的链接替换特定的标记词。

+0

问题尚不清楚。给一些示例 – JYoThI

回答

1

下面是完整的解决方案。

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

1

get_the_tags()将返回一个WP_Term对象的数组。您将不得不循环这些对象来构建您的$replace阵列。

例子:

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

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