I am working on editing a Wordpress plugin file.
The code below lists the categories in Alphabetical order. I want to list them by Category ID, in ascending order.
<?php foreach($categories as $category){
$rand = rand(0,99);
$catname = get_cat_name( $category );
$find = array("&", "/", " ","amp;","&");
$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 } ?>
I tried working with the get_cat_ID
function, but I'm not a programmer so I got stuck. Please help.
Rather than querying categories inside a theme file, a better way is to register a custom function in your wordpress theme.
Googling "wordpress category order by id" give me this link
https://wordpress.org/support/topic/how-to-order-my-categories-by-id-instead-of-name . The answer there is good.
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;
}
You can then call the function in your theme files which will return categories ordered by id. Something like that:
<?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 } ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.