我有一个自定义的帖子类型和分类法,当添加帖子时,如果我选择了一个子词而不是父词,那么我就不能使用get terms,因为父词不会在数组中,因为它没有被选中,所以我想知道是否可以使用子词来获取父词/id?
因为我要做一个if语句,所以如果一个post父项是(id 4),那么就显示一些东西。
所以我需要得到术语(所有术语都是子术语,使用子术语得到该术语的父术语)
我有一个自定义的帖子类型和分类法,当添加帖子时,如果我选择了一个子词而不是父词,那么我就不能使用get terms,因为父词不会在数组中,因为它没有被选中,所以我想知道是否可以使用子词来获取父词/id?
因为我要做一个if语句,所以如果一个post父项是(id 4),那么就显示一些东西。
所以我需要得到术语(所有术语都是子术语,使用子术语得到该术语的父术语)
在循环内部,您可以利用wp_get_post_terms()
返回与特定职位相关的所有条款。返回的此对象包含具有指定术语的所有属性的所有术语
考虑到这一点,您可以使用foreach
循环获取每个术语,然后检查每个术语的父级。对于孙子术语,您需要在此处进行一些额外检查,以确定父级或最高级术语父级
你可以这样做
$terms = wp_get_post_terms( $post->ID, \'category\' );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
if ( $term->parent == 4 ) {
//Do something if parent is 4
}
}
}
编辑要使用更深层的类别,可以使用get_ancestors()
获取所有级别并使用in_array()
测试特定类别ID您可以按如下方式扩展该功能:
$terms = wp_get_post_terms( $post->ID, \'category\' );
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
foreach ( $terms as $term ) {
if( $term->parent != 4 && $term->parent == 0 )
continue;
if ( $term->parent == 4 || in_array( 4, get_ancestors( $term->term_id, \'category\' ) )) {
//Do something if parent ID is 4
} else {
//Do nothing
}
}
}
我有以下表格(为了简洁明了,仅包含相关信息)表名称:wp\\U term\\U关系object_id term_taxonomy_id 1266 1341 1266 452 1266 449 表格名称:wp\\U term\\U taxonomyterm_taxonomy_id term_id 1341 1342 452 453