[英]Get category URL by category ID in WooCommerce on product details page
我在产品详细信息页面上查找类别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' );
获取产品类别的网址。
编辑确保product_cat_id是一个整数,使用以下行完全保存:
$link = get_term_link( (int)$product_cat_id, 'product_cat' );
如果产品属于一个或多个类别,则可以直接访问$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
是否为空并执行所需的操作。
代码经过测试和运行。
希望这可以帮助!
你可以使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.