I'm confused as to how to fetch the list of all the blog's categories (sans empty ones). I need the textual name and the URL to the cat archive as an array.

Do I use get_terms(), get_categories(), wp_list_categories(), wp_query() or something else?


get_categories() is just a wrapper for get_terms(), and you can use either function to get all the blog's categories which I assume are of the standard category taxonomy?; however, you can set a custom taxonomy when calling get_categories(), and one good reason to using get_categories() instead of get_terms() is that the output is always an array and not a WP_Error instance (even if get_terms() returned that instance).

wp_list_categories() is a higher level function which displays/echoes or retrieves the HTML list of categories, and the function uses get_categories() to get the categories list.

So if you want to get an array of the categories' name and (archive page) URL, then you'd want to use either get_categories() or get_terms(), but not wp_list_categories().

Here's an example using get_categories() and get_category_link() to get the category page's URL:

$cats = get_categories( 'hide_empty=0' );
if ( ! empty( $cats ) ) {
    echo '<ul>';
    foreach ( $cats as $term ) {
        $url = get_category_link( $term );
        echo '<li><a href="' . esc_url( $url ) . '">' . esc_html( $term->name ) . '</a></li>';
    echo '</ul>';

For the full list of accepted/supported parameters, see here for get_categories(), which actually points you to get_terms().

| improve this answer | |

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.