在Wordpress中更改类别列表顺序

时间:2015-04-26 01:52:41

标签: php wordpress

我正在编辑Wordpress插件文件。

下面的代码按字母顺序列出了类别。我想按类别ID按升序列出它们。

<?php foreach($categories as $category){ 
    $rand = rand(0,99);
    $catname = get_cat_name( $category );
    $find =     array("&", "/", " ","amp;","&#38;");
    $replace  = array("", "", "", "","");           
    $catname = str_replace($find,$replace,get_cat_name( $category ));
?>                  
    <li>
        <a href="#fragment-<?php echo $catname; ?>"><?php echo get_cat_name( $category ); ?></a>
    </li>
<?php } ?>

我尝试使用get_cat_ID功能,但我不是程序员,所以我卡住了。请帮忙。

1 个答案:

答案 0 :(得分:0)

不是在主题文件中查询类别,更好的方法是在wordpress主题中注册自定义函数。

通过ID&#34;谷歌搜索&#34; wordpress类别订单给我这个链接

https://wordpress.org/support/topic/how-to-order-my-categories-by-id-instead-of-name。答案很好。

add_filter('get_the_categories','get_the_category_sort_by_id');

function get_the_category_sort_by_id( $categories ) {
    usort($categories, '_usort_terms_by_ID');
    return $categories;
}

然后,您可以在主题文件中调用该函数,该函数将返回按ID排序的类别。这样的事情:

<?php
$categories = get_the_category_sort_by_id($categories);
foreach($categories as $category){ 
    ...
?>
    <li>
        <a href="#fragment-<?php echo $catname; ?>"><?php echo get_cat_name( $category ); ?></a>
    </li>
<?php } ?>
相关问题