I'm filtering my WooCommerce Products on a custom page template by category and a custom meta_key. Now I'm trying to echo the category name in which the products are filtered.
The url after filtering the products looks like
.../online-shop/popular-products/?product-cato=23
23 is the ID of the Category. I was able to get (or echo) the id by using the following
<?php echo sanitize_text_field($_GET['product-cato']);?>
Any idea how to get the category name with the available category ID (in this case 23)?
You could try to use the following:
// 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>';
}
Tested and works.
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.