简体   繁体   中英

Wordpress - Multiple categories in a category page

I have a problem on my category template. I use the function get_the_category() to get the current category of the page.

I take the first one of the array to select the posts and show in my custom menu the current category.

It works well for all my categories except for one. In this category (which is exactly the same as the others, no particularities), get_the_category() return 2 categories instead of one, and the first category of the array is not the good one.

How can I fix this ?

EDIT : This is the return array of the get_the_category() function :

Array
(
    [0] => WP_Term Object
    (
        [term_id] => 152
        [name] => Press
        [slug] => press
        [term_group] => 0
        [term_taxonomy_id] => 152
        [taxonomy] => category
        [description] => Press
        [parent] => 0
        [count] => 46
        [filter] => raw
        [object_id] => 32182
        [cat_ID] => 152
        [category_count] => 46
        [category_description] => Press
        [cat_name] => Press
        [category_nicename] => press
        [category_parent] => 0
    )

[1] => WP_Term Object
    (
        [term_id] => 178
        [name] => The Fundation
        [slug] => the-fundation
        [term_group] => 0
        [term_taxonomy_id] => 178
        [taxonomy] => category
        [description] => 
        [parent] => 0
        [count] => 10
        [filter] => raw
        [object_id] => 32182
        [cat_ID] => 178
        [category_count] => 10
        [category_description] => 
        [cat_name] => The Fundation
        [category_nicename] => the-fundation
        [category_parent] => 0
    )

)

I got this for the category page the-fundation

Try this.

$categories = get_the_category();
$category_id = $categories[0]->cat_ID;

or

get_query_var('cat');

get_the_category() returns an array of WP_Term objects (categories) assigned to the current post, it does not return the current category. If you're on a category page it'll default to using the first post within that category.

To get the current category you'd be better off calling get_queried_object() on the category page:

$category = get_queried_object();

if ( $category instanceof WP_Term ) {
    $category_id = $category->term_id;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM