我正在产品详细信息页面上查找类别 URL。我正在使用下面的代码来获取类别 ID,但我不确定如何获取类别 URL。
<?php
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
echo $product_cat_id = $term->term_id;
break;
}
我正在产品详细信息页面上查找类别 URL。我正在使用下面的代码来获取类别 ID,但我不确定如何获取类别 URL。
<?php
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
echo $product_cat_id = $term->term_id;
break;
}
如果您有id
可以使用的产品类别
$link = get_term_link( $product_cat_id, 'product_cat' );
获取产品类别的 url。
编辑确保 product_cat_id 是整数,使用以下行完全保存:
$link = get_term_link( (int)$product_cat_id, 'product_cat' );
您可以使用get_category_link(int|object $category)
https://developer.wordpress.org/reference/functions/get_category_link/
在这里我如何在' content-product_cat.php
'上使用它
<a href="<?php esc_url_e( get_category_link( $category->term_id ) ); ?>">
<h5 class="product-name"><?php esc_attr_e( $category->name ); ?></h5>
<span class="dima-divider line-center line-hr small-line"></span>
<span class="count">
<?php if ( $category->count > 0 ) {
echo apply_filters( 'woocommerce_subcategory_count_html', $category->count . ' ' . ( $category->count > 1 ? __( 'Products', 'woocommerce' ) : __( 'Product', 'woocommerce' ) ), $category );
}?>
</span>
</a>
如果产品属于一个或多个类别,那么您可以直接访问该$terms[0]
位置并检索 URL
这是代码:
global $post;
$link = '';
$terms = get_the_terms( $post->ID, 'product_cat' );
if(!empty($terms[0])){
$link = get_term_link( $terms[0]->term_id, 'product_cat' );
}
现在只需检查是否$link
为空并执行您需要的操作。
代码经过测试并且可以工作。
希望这可以帮助!