0

I use the following code to get a list of all categories:

$args = array(
    'hide_empty' => 0,
    'orderby'    => 'name'
);
wp_list_categories($args);

However, I want a list that only lists categories related to posts. How can I achieve this?

1
  • 'hide_empty' => 1,?
    – kero
    Jul 13, 2017 at 14:20

1 Answer 1

0
<!-- Display Categories Assigned to a post -->

                    <?php $taxonomy = 'category';

                    // Get the term IDs assigned to post.
                    $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );

                    // Separator between links.
                    $separator = ',';
 if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {

                        $gterms = wp_list_categories( array(
                            'title_li' => '',
                            'style'    => 'none',
                            'echo'     => false,
                            'taxonomy' => $taxonomy,
                            'include'  => $term_ids,
                            'child_of' => 193
                        ) );

                        $gterms = rtrim( trim( str_replace( '<br />',  $separator, $gterms ) ), $separator );
                    }

put your parent cat id, for example, I have genre parent category, it has a lot of children, to display the children that are related to the current post you're in put the id of the parent which is genre. to output it plz use <?php echo $gterms; ?>

2
  • Thank you! However, what I really want to achieve is, to get every category that is used by any post. So I want a list of categories, that are generally used by posts. Jul 13, 2017 at 15:12
  • you mean the most used categories?!
    – Ashley
    Jul 13, 2017 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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