我已经在我的WordPress主题文件夹中创建了一个taxonomy.php页面。我想要在一个函数中获取当前分类词的ID,你可以告诉我如何做吗?
get_query_var('taxonomy')
只返回分类词的别名(slug),而我想要ID。没事了!我找到了 :)
get_queried_object()->term_id;
简单易懂!
get_queried_object_id()
get_queried_object_id()
是在WordPress 3.1.0(2011年2月23日)中引入的函数,可用于获取当前页面的ID。如果您想在WordPress模板文件夹中的taxonomy.php
页面中使用该函数以获取当前术语ID,那么它应该是您需要的正确答案。 - Pea以下是所需的完整代码段:
$queried_object = get_queried_object();
$term_id = $queried_object->term_id;
使用以下代码
这将打印您当前的分类法名称和描述(可选)
<?php
$tax = $wp_query->get_queried_object();
echo ''. $tax->name . '';
echo "<br>";
echo ''. $tax->description .'';
?>
如果您在分类法页面。
这是获取有关分类法的所有详细信息的方法。
get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
这是获取分类法 ID 的方法
$termId = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) )->term_id;
但如果您在文章页面(分类法 -> 子级)
$terms = wp_get_object_terms( get_queried_object_id(), 'taxonomy-name');
$term_id = $terms[0]->term_id;
<?php
$terms = get_the_terms( $post->ID, 'taxonomy');
foreach ( $terms as $term ) {
$termID[] = $term->term_id;
}
echo $termID[0];
?>
请参见wp_get_post_terms(),你可以这样做:
global $post;
$terms = wp_get_post_terms( $post->ID, 'YOUR_TAXONOMY_NAME',array('fields' => 'ids') );
print_r($terms);
你需要的是术语“slug”。如果你需要id,可以像这样获取:
function get_term_link( $term, $taxonomy = '' ) {
global $wp_rewrite;
if ( !is_object($term) ) {
if ( is_int( $term ) ) {
$term = get_term( $term, $taxonomy );
} else {
$term = get_term_by( 'slug', $term, $taxonomy );
}
}
这适用于所有页面类型,而不仅仅是分类术语存档
$category_id = get_the_category( get_the_ID());
$id = get_category($category_id[0]->term_id);
get_queried_object_id()
来仅检索 ID。整个代码片段将是$term_id = get_queried_object_id();
。 - David