2015-08-22 136 views
2

标记链接我要添加过滤器来修改在WP get_the_tag_list生成的链接。它调用了get_the_term_list添加过滤器添加类在WordPress

function get_the_term_list($id, $taxonomy, $before = '', $sep = '', $after = '') { 
$terms = get_the_terms($id, $taxonomy); 

if (is_wp_error($terms)) 
    return $terms; 

if (empty($terms)) 
    return false; 

$links = array(); 

foreach ($terms as $term) { 
    $link = get_term_link($term, $taxonomy); 
    if (is_wp_error($link)) { 
     return $link; 
    } 
    $links[] = '<a href="' . esc_url($link) . '" rel="tag">' . $term->name . '</a>'; 
} 

我想补充class="tag",但我不知道如何写一个过滤器为我functions.php文件的目标只有$links[]位该功能的。我可以排除旧的链接集并以某种方式添加我的修改过的链接集吗?

我想加入这样的事情,但我有它在某种程度上错误:

add_filter('get_the_term_list','replace_content'); 
function replace_content($links[]) 
{ 
    $links[] = str_replace('<a href="', '<a class="tag" href="', $links[]); 
    return $links[]; 
} 
+0

你使用哪种版本的WordPress的?这仅仅是为了'标签'分类吗? – TeeDeJee

+0

其版本4.3 – antonanton

回答

3

你犯了几个错误。首先在get_the_term_list上添加过滤器将不起作用,因为它不是过滤器。如果您在get_the_term_list代码看,你会看到这样一行(取决于您的WP版本)

$term_links = apply_filters("term_links-$taxonomy", $term_links); 

所以,你可以在你的情况下,上term_links-$taxonomy添加过滤器的分类是标签。

所做的第二个错误是在与阵列结合str_replace。如果你想使用一个数组,你不需要在变量之后添加[]。这仅用于将=之后的部分分配给数组中的下一项。在这种情况下,你的整个阵列上做了str_replace所以你应该使用$links代替$links[]无论是在分配和在str_replace,否则你将你的当前阵列的所有环节后添加一个新阵列(与字符串替换)。

add_filter("term_links-post_tag", 'add_tag_class'); 

function add_tag_class($links) { 
    return str_replace('<a href="', '<a class="tag" href="', $links); 
} 
+0

感谢您的解释! 我有这个在我的版本: '$ term_links = apply_filters( “term_links- $分类学”,$链接);'。 并回答你的其他问题,只有它的标签。我使用这些标签作为人名,所以我想为这些类添加一个'no-wrap'类,以便在这些类中不会打破名称。想你的版本,但我似乎并没有注意到它没收$联系挂钩作为类不适用 – antonanton

+0

@antonanton我的错误,它应该是term_links-post_tag代替term_links标签。看我的编辑。 – TeeDeJee

+0

thx @TeeDeJee,工作正常。比我想象的要简单得多 – antonanton