自定义的文章类型发布的文章,在当前页面中想要获取其父级分类链接就不能用get_the_category()方法了。
因为这种方法只能使用在默认的Category分类系统。
但是自定义文章类型的分类跟默认的分类系统不一样。
在这种情况下,需要使用get_the_terms()来实现了。
下面的函数将返回当前页面的父级分类的链接。
function wpdocs_custom_taxonomies_terms_links() {
$post = get_post( $post->ID );
$post_type = $post->post_type;
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
foreach ( $taxonomies as $taxonomy_slug => $taxonomy ) {
$terms = get_the_terms( $post->ID, $taxonomy_slug );
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) {
$out = esc_url( get_term_link( $term->slug, $taxonomy_slug ) );
//$out = esc_html( $term->name ); // 返回父级分类名称。
}
}
}
return $out;
}
echo wpdocs_custom_taxonomies_terms_links();
评论区
发表新的留言
您可以留言提出您的疑问或建议。
您的留言得到回复时,会通过您填写的邮箱提醒您。