最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get all the blog's categories and the related URLs?

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Jun 11, 2019 at 9:26 Matthew Brown aka Lord MattMatthew Brown aka Lord Matt 1,0683 gold badges13 silver badges34 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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().

发布评论

评论列表(0)

  1. 暂无评论