2014-10-16 43 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