Home > Back-end >  get list of categoris from a specific post with get_term()
get list of categoris from a specific post with get_term()

Time:03-08

I want to get a list of categories from a post. and them hide a specific category with all child

    $args = array(
                            'orderby' => 'term_order',
                            'exclude_tree' => array('vip'),
                            'fields' => array('names', 'slugs'),
                            'term_id' => $current_post_id,
                            'taxonomy' => 'category',                        
                             );

                            $terms = get_terms($args);

                            var_dump($terms);

but I got a null array. I know I have a stupid problem. because I am new to WordPress

UPDATE: my problem is about to add 'taxonomy' => 'category' and give a integer to exclude_tree

right now I correct my code and its work but I have a problem with that

                    $args = array(
                        'orderby' => 'term_order',
                         'exclude_tree' => [2621],
                        'fields' => 'names',
                    );

                    try {

                        $terms = wp_get_post_categories($current_post_id,$args);

It seems 'fields' just get one string. I want to get the name of the category with their link.

CodePudding user response:

Add the taxonomy name (or array of names) to your $args array - you can refer to the list of available args at https://developer.wordpress.org/reference/classes/wp_term_query/__construct/ but you'll want something like

'taxonomy' => 'category',
or similar.

CodePudding user response:

The WP_Term object does not include the permalink, so the fields arg won't help with that. You can remove it to get the whole term object, then to get the permalink, you'd do

get_term_link( $term, $taxonomy );

where $term is the ID or slug or the whole term object and $taxonomy in your case is 'category'.

  • Related