Wordpress 从单个 Post、多个类别中获取当前类别

Wordpress Get the CURRENT Category from Single Post, Multiple Categories

我有一个自定义 Post 类型的 家庭计划 和一个自定义分类 社区

相同的家庭计划出现在多个不同的社区

永久链接已设置,现在我正在尝试找到我正在查看 家庭计划.

因为 Home Plan 出现在多个 Communities 中,以下示例链接都将您带到 same 家庭计划 如预期:

为了显示基于社区的相关信息,我试图找到一种方法来确定当前 社区.

在我的 single-home-plans.php 文件中,我打印了 get_query_object();和 get_the_terms();但我还没有找到任何有用的东西。

一个可能的解决方法是传递一个 $_GET 值,但在这一点上这绝对是最后的手段。

当您在单个页面上时,没有当前分类法这样的东西。您只能检查从哪个分类用户转到此页面。您可以通过检查 $_SERVER['HTTP_REFERER'].

来做到这一点

假设您的 url 与您提供的一样简单,这可能就可以了,

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

如果在分类中将 query_var 设置为 true,您可以使用 $wp_query(全局)、

检测当前正在查看的类别

$wp_query->query_vars['the_taxonomy_name'];

运行 var_dump($wp_query->query_vars); 查看所有查询信息的完整数组。

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