To display a search category name in WordPress, you typically want to check if the current query is for a specific category and then retrieve its name. Here's how you can achieve this:
If you're on a category archive page, you can use the single_cat_title()
function to display the category name.
<?php
if (is_category()) {
single_cat_title();
}
?>
If you have a search query that filters by a category (e.g., via a dropdown or URL parameter), you can retrieve the category name using the get_category_by_slug()
or get_term()
function.
Here’s an example assuming the category is passed via a cat
parameter in the query:
<?php
if (is_search() && isset($_GET['cat']) && !empty($_GET['cat'])) {
$category_id = intval($_GET['cat']);
$category = get_category($category_id);
if ($category) {
echo esc_html($category->name);
} else {
echo "Category not found.";
}
}
?>
If you're working with a custom taxonomy instead of categories, you can use a similar approach:
<?php
if (is_tax('your_custom_taxonomy')) {
single_term_title();
}
?>
If you want to show the category name dynamically in a dropdown, you can populate it using wp_dropdown_categories()
:
<?php
wp_dropdown_categories([
'show_option_all' => 'All Categories',
'name' => 'cat',
'selected' => get_query_var('cat'),
]);
?>
esc_html()
or similar functions.To display the tag name in WordPress, you can use the following approaches based on your context:
If you are on a tag archive page, you can use single_tag_title()
to display the current tag name:
<?php
if (is_tag()) {
single_tag_title();
}
?>
If you're using a search form or URL to filter by tag (e.g., a tag
query parameter), you can retrieve the tag name using get_term_by()
.
Here’s an example:
<?php
if (is_search() && isset($_GET['tag']) && !empty($_GET['tag'])) {
$tag_slug = sanitize_text_field($_GET['tag']);
$tag = get_term_by('slug', $tag_slug, 'post_tag');
if ($tag) {
echo esc_html($tag->name);
} else {
echo "Tag not found.";
}
}
?>
If you are working with a custom taxonomy instead of the default post_tag
, use the following:
<?php
if (is_tax('your_custom_taxonomy')) {
single_term_title();
}
?>
Replace your_custom_taxonomy
with the slug of your taxonomy.
If you want to show the tag name dynamically in a dropdown, you can use wp_tag_cloud()
or a custom query:
wp_tag_cloud
:<?php
wp_tag_cloud([
'taxonomy' => 'post_tag',
'format' => 'flat', // or 'list'
'smallest' => 8,
'largest' => 22,
]);
?>
<?php
$tags = get_terms([
'taxonomy' => 'post_tag',
'hide_empty' => false,
]);
if (!empty($tags) && !is_wp_error($tags)) {
echo '<select name="tag">';
echo '<option value="">All Tags</option>';
foreach ($tags as $tag) {
echo '<option value="' . esc_attr($tag->slug) . '">' . esc_html($tag->name) . '</option>';
}
echo '</select>';
}
?>
esc_html()
for output and sanitize input using sanitize_text_field()
or similar.tag
query parameter, or adapt the code to your setup.