2014-10-16 39 views
0

我做了这个剧本,如何在foreach WordPress模板中获取tag_description?

<?php 
function top_tags() { 
    $tags = get_tags(); 

    if (empty($tags)) 
     return; 

    $counts = $tag_links = array(); 
    foreach ((array) $tags as $tag) { 
     $counts[$tag->name] = $tag->count; 
     $tag_links[$tag->name] = get_tag_link($tag->term_id); 
    } 

    asort($counts); 
    $counts = array_reverse($counts, true); 

    $i = 0; 
    foreach ($counts as $tag => $count) { 
     $i++; 
     $tag_link = clean_url($tag_links[$tag]); 
     $tag = str_replace(' ', '&nbsp;', wp_specialchars($tag)); 
     if($i < 11){ 
      print "<li><a href=\"$tag_link\">$tag ($count) </a></li>"; 
     } 
    } 
} 
?> 

但我似乎无法得到每个标签的tag_description。如果我在foreach函数中使用$description = tag_description();,它不会显示任何内容。

回答

1

......怎么这样:

<?php 
function top_tags() { 
    $tags = get_tags(); 

    if (empty($tags)) 
     return; 

    $counts = $tag_links = array(); 
    foreach ((array) $tags as $tag) { 
     $counts[$tag->name] = $tag->count; 
     $tag_links[$tag->name] = get_tag_link($tag->term_id); 
    } 

    asort($counts); 
    $counts = array_reverse($counts, true); 

    $i = 0; 
    foreach ($counts as $tag => $count) { 
     $i++; 
     $tag_link = clean_url($tag_links[$tag]); 
     $tag_description = tag_description(get_term_by('name', $tag, 'post_tag')->term_id); 
     $tag = str_replace(' ', '&nbsp;', wp_specialchars($tag)); 
     if($i < 11){ 
      print "<li><a href=\"$tag_link\">$tag ($count) </a> $tag_description </li>"; 
     } 
    } 
} 
?> 

一个这样做(未经测试)的更有效的方法:

<?php 
function top_tags() { 
    $tags = get_tags(); 

    if (empty($tags)) 
     return; 

    $counts = $tag_links = array(); 
    foreach ((array) $tags as $tag) { 
     $counts[$tag->name] = $tag->count; 
     $tag_links[$tag->name] = array('url' => get_tag_link($tag->term_id), 'description' => $tag->description); 
    } 

    asort($counts); 
    $counts = array_reverse($counts, true); 

    $i = 0; 
    foreach ($counts as $tag => $count) { 
     $i++; 
     $tag_link = clean_url($tag_links[$tag]['url']); 
     $tag_description = $tag_links[$tag]['description']; 
     $tag = str_replace(' ', '&nbsp;', wp_specialchars($tag)); 
     if($i < 11){ 
      print "<li><a href=\"$tag_link\">$tag ($count) </a> $tag_description </li>"; 
     } 
    } 
} 
?> 
+0

不,仍然没有看到。尽管感谢您的回答。 – Siyah 2014-10-16 11:32:32

+0

您上次编辑的作品。谢谢你,谢谢! – Siyah 2014-10-16 11:33:21

+0

你有没有试过我的编辑?标签更改为“post_tag”中的get_term_by – 2014-10-16 11:33:37

1

只是对你的想法发表意见,这不应该使用,你可以使用tag_descriptionforeach循环内如下

$description = tag_description($tag->term_id); 

以上方法我不是错,但get_tags已经返回标签说明您可以返回如下

$tag->description 

编辑

看到的是由get_tags返回,请执行下列操作

$tags = get_tags; 
?><pre><?php var_dump($tags); ?></pre><?php 
+0

感谢彼得。很高兴了解这些条款的新内容。 Bedankt。 – Siyah 2014-10-16 11:39:27