通过 GET 请求的 ID 获取 Woocommerce 产品类别名称
Get Woocommerce product Category Name by it's ID from a GET request
我正在按类别和自定义 meta_key 在自定义页面模板上过滤我的 Woocommerce 产品。现在我试图回应产品被过滤的类别名称。
商品筛选后的url是
.../online-shop/popular-products/?product-cato=23
23 是类别的 ID。我能够通过使用以下
获取(或回显)ID
<?php echo sanitize_text_field($_GET['product-cato']);?>
知道如何使用可用的类别 ID(在本例中为 23)获取类别名称吗?
您可以尝试使用以下方法:
// Testing that $_GET['product-cato'] has been requested and that the product category exists.
if( isset( $_GET['product-cato'] ) && term_exists( intval($_GET['product-cato']), 'product_cat' ) ){
// Get the corresponding WP_Term object
$term = get_term( intval($_GET['product-cato']), 'product_cat' );
//Display the term name for the product category
echo '<p>' . $term->name . '</p>';
}
已测试并有效。
You will not need to sanitize the Product category name, as it's already filtered by the conditions and by intval()
function. So it's secure.
我正在按类别和自定义 meta_key 在自定义页面模板上过滤我的 Woocommerce 产品。现在我试图回应产品被过滤的类别名称。
商品筛选后的url是
.../online-shop/popular-products/?product-cato=23
23 是类别的 ID。我能够通过使用以下
获取(或回显)ID<?php echo sanitize_text_field($_GET['product-cato']);?>
知道如何使用可用的类别 ID(在本例中为 23)获取类别名称吗?
您可以尝试使用以下方法:
// Testing that $_GET['product-cato'] has been requested and that the product category exists.
if( isset( $_GET['product-cato'] ) && term_exists( intval($_GET['product-cato']), 'product_cat' ) ){
// Get the corresponding WP_Term object
$term = get_term( intval($_GET['product-cato']), 'product_cat' );
//Display the term name for the product category
echo '<p>' . $term->name . '</p>';
}
已测试并有效。
You will not need to sanitize the Product category name, as it's already filtered by the conditions and by
intval()
function. So it's secure.