2

I have a sample:

CODE PHP:

 <ul class="categories-list">
        <?php wp_list_categories('title_li='); ?>
 </ul>

This code displays the category list sorted by name.

What I want to do is to have a custom order ... not by name not by id.

For example, this order:

   1. Category with ID 5:

   2. Category with ID 3:

   3. Category with ID 9:

How can I do this using the function above?

3

You will need to add term meta to your categories. In this metafield you will store the string or number that you want to use as a base for your custom order (tutorial). Let's say you have generated a meta field called my_cat_meta which holds integers that say in which order you want them to be displayed.

Now you can pass this metakey to wp_list_categories. This function ultimately relies on get_terms, which explains which arguments the function can take. You can limit the search to terms that have the metakey defined and order according to that metakey. This amounts to:

$args = array (
  'title_li' -> '',
  'meta_key' -> 'my_cat_meta',
  'orderby'-> 'meta_key');
wp_list_categories ($args);

A slightly hacky way would be to use the 'description' field that is a default field in WP categories. Many themes don't display it, so you could use it to store metadata. In that case you could skip building your own metafield and use:

$args = array (
  'title_li' -> '',
  'orderby'-> 'description');
wp_list_categories ($args);
1

You can use the shuffle() function to get the categories in random order. Like this,

$categories = get_categories();
shuffle( $categories );

Hope this works for you!

  • i think it will only shuffle $categories items every time its gets executed. – Harry Mar 28 '17 at 11:18
1

wp_list_categories(); give you formatted output,

To display elements for custom layout you can use get_categories() or get_terms() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.