WordPress Get the CURRENT Category from Single Post, Multiple Categories

I’ve got a Custom Post Type of Home Plan and a Custom Taxonomy of Community.

The same Home Plan appears in multiple different Communities.

Read More

Permalinks have been set, and now I’m trying to find the current Community from which I’m viewing the Home Plan.

Because the Home Plan appears in multiple Communities, the following example links all take you to the same Home Plan as intended:

  • domain.com/community-name-1/plan-name
  • domain.com/community-name-2/plan-name
  • domain.com/community-name-3/plan-name

In order to display the relevant information based on the Community, I’m attempting to find a way to determine the current Community.

In my single-home-plans.php file, I’ve printed get_query_object(); and get_the_terms(); but I haven’t found anything useful.

A possible workaround would be to pass a $_GET value, but at this point that’s an absolute last resort.

Related posts

3 comments

  1. No such thing as current taxonomy, when you on single page. You can only check from which taxonomy user go to this page. You can do this by checking $_SERVER[‘HTTP_REFERER’].

  2. Assuming your url are as simple as what you’ve provided, this will probably do,

    // Get the Current  URL path
    $url =  "{$_SERVER['REQUEST_URI']}";
    
    // Convert URL path string to array
    $e = explode('/', $url ); // You can dump this to verify which is the taxonomy slug
    
    // Get all taxonomy slug assigned on this post
    $taxonomy = wp_get_post_terms( get_the_ID(), 'your_taxonomy');
    $tax_names = '';
    foreach( $taxonomy as $tax ) {
        $tax_names .= ' '. $tax->slug;
    }
    // check if 2nd array which is the current taxonomy exist on list of taxonomy assigned to post
    if( isset( $e[1] ) && strpos($tax_names, $e[1]) !== false ) {
        // Get Term Name by slug
        $term = get_term_by('slug', $e[1], 'your_taxonomy');
        _e( $term->name);
    } else {
        _e($e[1]. ' is not a valid taxonomy for this post');
    }
    
  3. If query_var is set to true in the taxonomy, you can detect which category is currently being viewed by using $wp_query (global),

    $wp_query->query_vars['the_taxonomy_name'];

    Run var_dump($wp_query->query_vars); to view the full array of all query information.

    <?php global $wp_query;
    $home_plan_community = $wp_query->query_vars['community'];
    echo $home_plan_community; ?>
    

Comments are closed.