WordPress – Sorting Categories By Category

Sorting categories in wordpress is not difficult, because the parameters are already available in the wp_list_categories() function, with that function we can sort categories by ID, name, slug, count or term_group, but there are times when we are asked to sort based on the last post we made . This is a bit difficult. For example, the last post is about the economy, so the categories that appear start from the economy.

The main logic if you want to sort like that means we have to query the posts first, after that only the mapping category.

Cekidot, hope it helps your problem.

$cat_array = array();
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => 25,
‘caller_get_posts’=> 1

if ($cat_array) {
  foreach($cat_array as $cat) {
    $category = get_term_by('ID',$cat, 'category');
    echo '&lt;a href=&quot;' . esc_attr(get_term_link($category, 'category')) . '&quot; title=&quot;' . sprintf( __( &quot;View all posts in %s&quot; ), $category-&gt;name ) . '&quot; ' . '&gt;' . $category-&gt;name.'&lt;/a&gt;'.'&lt;br /&gt;';

Ref: Dynamic WP