通过GET请求获取Woocommerce产品类别名称ID

时间:2018-01-30 22:04:08

标签: php wordpress woocommerce categories custom-taxonomy

我按类别和自定义元标记在自定义页面模板上过滤我的Woocommerce产品。现在我试图回应产品被过滤的类别名称。

过滤产品后的网址如

.../online-shop/popular-products/?product-cato=23

23是类别的ID。我能够通过使用以下

获得(或回显)id
<?php echo sanitize_text_field($_GET['product-cato']);?>

知道如何使用可用的cateogry ID获取类别名称(在本例中为23)?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用以下内容:

// 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>';
}

经过测试和工作。

  

您将不需要清理产品类别名称,因为它已经按条件和intval()功能进行了过滤。所以它很安全。