WordPress开发笔记

WordPress获取某篇文章在特定分类法(taxonomy)下的分类(term)

在WordPress中,如果你想获取某篇文章在特定分类法(taxonomy)下的分类(term),可以使用以下方法:

方法一:使用 wp_get_post_terms() 函数

wp_get_post_terms() 是 WordPress 提供的一个函数,用于获取文章在指定分类法下的分类。

$post_id = get_the_ID(); // 获取当前文章的ID
$taxonomy = 'tax'; // 分类法名称
$terms = wp_get_post_terms($post_id, $taxonomy);

if (!is_wp_error($terms) && !empty($terms)) {
    foreach ($terms as $term) {
        echo $term->name; // 输出分类名称
    }
} else {
    echo '没有找到分类';
}

方法二:使用 get_the_terms() 函数

get_the_terms() 是另一个常用的函数,用于获取文章在指定分类法下的分类。

$post_id = get_the_ID(); // 获取当前文章的ID
$taxonomy = 'tax'; // 分类法名称
$terms = get_the_terms($post_id, $taxonomy);

if (!is_wp_error($terms) && !empty($terms)) {
    foreach ($terms as $term) {
        echo $term->name; // 输出分类名称
    }
} else {
    echo '没有找到分类';
}

方法三:使用 get_terms() 函数

如果你知道文章ID和分类法名称,也可以使用 get_terms() 函数来获取分类。

$post_id = get_the_ID(); // 获取当前文章的ID
$taxonomy = 'tax'; // 分类法名称
$terms = get_terms(array(
    'taxonomy' => $taxonomy,
    'object_ids' => $post_id,
));

if (!is_wp_error($terms) && !empty($terms)) {
    foreach ($terms as $term) {
        echo $term->name; // 输出分类名称
    }
} else {
    echo '没有找到分类';
}

方法四:使用 get_the_term_list() 函数

如果你想直接输出分类的链接,可以使用 get_the_term_list() 函数。

$post_id = get_the_ID(); // 获取当前文章的ID
$taxonomy = 'tax'; // 分类法名称
$term_list = get_the_term_list($post_id, $taxonomy, '', ', ', '');

if (!is_wp_error($term_list) && !empty($term_list)) {
    echo $term_list; // 输出分类链接
} else {
    echo '没有找到分类';
}

总结

  • wp_get_post_terms()get_the_terms() 是最常用的方法,适合获取文章的分类信息。
  • get_terms() 适合在需要更复杂的查询时使用。
  • get_the_term_list() 适合直接输出分类链接。

根据你的需求选择合适的方法即可。