php - Wordpress Get the CURRENT Category from Single Post, Multiple Categories

493

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.

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.

815

Answer

Solution:

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'].

738

Answer

Solution:

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');
}
484

Answer

Solution:

Ifquery_var is set totrue in the taxonomy, you can detect which category is currently being viewed by using$wp_query (global),

$wp_query->query_vars['the_taxonomy_name'];

Runvar_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; ?>

People are also looking for solutions to the problem: php - Storing hourly updated data in MySql

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.