How to get taxonomy term of the current page and populate queries in the template

I’ve been stumbling around trying to figure out how to get a specific taxonomy term of the current page so that I can subsequently populate queries on the page for other post types that share the same term.

Basically:

  • Page 1 has taxonomy term – education policy
  • page.php has four parts:
    1. standard loop that outputs the page, but then has three subsequent queries
    2. loop for events that have taxonomy term – education policy
    3. loop for reports that have taxonomy term – education policy
    4. loop for people that have taxonomy term – education policy

I did page specific templates where I could just hardcode the term into the extra loops, but I need to figure out how to do it dynamically (what was originally supposed to be four or five pages is now forty or fifty).

I’ve found a few similar questions, but none that I could really find my way through implementing.

Get current page's taxonomy
which was a little confusing to follow in terms of what was actually being asked.

Get the term id belonging to custom taxonomy on a custom single-post-type.php template page

I hope this makes sense and many thanks.

Solutions Collecting From Web of "How to get taxonomy term of the current page and populate queries in the template"

Hm, if you registered a taxonomy for the “page” object type correctly and then assigned a term of that taxonomy to a page… I believe you can then access the taxonomy and term slugs in the following way:

get_query_var( 'taxonomy' )
get_query_var( 'term' )

If you print_r($wp_query) you will see all the parameters that are there when generating a current page that’s displayed. With code above you’re accessing those parameters from $wp_query.

Then to get the term object with full info you can use get_term_by function, like so

$term = get_term_by( 'slug', get_query_var('term'), get_query_var('taxonomy') );
echo $term->name;

This will print the “nice” name of the term.

I believe if you use get_query_var('term') or $term->slug (after getting the term object) you can use that slug in all of other queries.

Hope that helps. I never used taxonomy for pages.
Let me know how you get on.

Just copy paste below code

This will print your current page taxonomy name & description (optional)

<?php 
   $tax = $wp_query->get_queried_object();
   echo ''. $tax->name . '';
   echo "<br>";
   echo ''. $tax->description .''; 
?>

May be you need to enable search to enable pagination

While declaring custom taxonomy you should disable search excluding.

exclude_from_search => false

This fixed my problem.