WordPress自定义文章类型单页输出当前分类slug失败求助
WordPress 自定义文章类型单页分类Slug输出问题修复
你的代码存在几个关键问题,导致无法正常输出分类slug:
wp_get_post_terms第一个参数需传入文章ID,而非文章slug,正确参数应为get_the_ID()或$post->ID- 从你的链接
product-category判断,自定义文章类型product的分类应该是自定义分类法product_category,而非默认的category wp_get_post_terms返回的是分类对象数组,不能直接通过$terms->slug访问,需先判断数组是否有效,再取第一个分类的slug- 硬编码相对路径
../../product-category/易出现路径错误,建议用WordPress内置函数get_term_link()生成可靠的分类链接
修正后的代码如下:
if ( 'product' == get_post_type() ) { // 获取当前文章关联的product_category分类 $terms = wp_get_post_terms( get_the_ID(), 'product_category' ); // 确保获取到有效分类数据 if ( ! empty( $terms ) && ! is_wp_error( $terms ) ) { $term = $terms[0]; ?> <center><a href="<?php echo esc_url( get_term_link( $term ) ); ?>" class="grve-btn grve-btn-small grve-square grve-bg-primary-1 grve-bg-hover-black">Back</a></center> <?php } }
内容的提问来源于stack exchange,提问作者Octavian Djemangin
相关产品推荐
相关产品推荐

