What I would like to achieve is getting the posts categories and subcategories (without needing subcategories to be related to this post) (when viewing the post) in a list outside of the loop, preferably in a sidebar widget. I want it to get updated automatically when displaying different posts without needing the user to specify the categories or posts manually from back-end. I tried with GLOBALS but couldn't get it to work.

Anyone done anything like this before? How should I approach?

Thanks in advance.

  • get_queried_object_id() should return the id, Just tested with my stock _s theme. var_dump(get_queried_object_id()); returning int(9511) . Are you sure your sidebar or something else is not modifying the query? Can you try wp_reset_postdata() before your code? Commented Mar 9, 2020 at 16:59
  • @SahriarSaikat thanks for your reply, I will remove the code - above code returns sub-categories only if they are associated with the post. Does nothing like what I want. I am at the beginning again.
    – Arg Geo
    Commented Mar 9, 2020 at 17:04
  • Dump get_queried_object_id() in sidebar and see what it returns Commented Mar 9, 2020 at 17:07
  • It returns the page id, correctly.
    – Arg Geo
    Commented Mar 9, 2020 at 17:14

1 Answer 1


You can use this in your sidebar.php. I highly recommend you to use a child theme.

Here is a minimum example of such a tag list. you can also make a widget out of it. Learn here.

And add html based on your theme's design structure.

$terms = wp_get_post_terms( get_queried_object_id(), 'taxonomy-name-here' );
foreach($terms as $term){
        <a href="<?php echo get_term_link( $term ); ?>"><?php echo $term->name; ?></a>
<?php } ?>
  • prntscr.com/rdtt83 this is what I am trying to achieve.
    – Arg Geo
    Commented Mar 9, 2020 at 17:24
  • You post this code in sidebar.php Commented Mar 9, 2020 at 17:27
  • I have added more info Commented Mar 9, 2020 at 17:27
  • Won't this display only terms related to the post?
    – Arg Geo
    Commented Mar 9, 2020 at 17:29
  • And Stackoverflow is more about solving your problems, not asking others to do your homework, please do your research first. Commented Mar 9, 2020 at 17:29

Your Answer

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

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