0

I have a function in a theme:

$category = isset($_GET['category']) ? wp_unslash($_GET['category']) : '';

The problem is that it outputs my categories like this:

"test-category"

I want, however, to show: "Test Category", just like it's saved in the backend, without the dashes and the smaller letters.

Is there a way I can get rid of this slug and use the nicename instead? I tried a lot of things (like the get_term_by() function), but nothing works for me. I guess it's because of the fact that I am using the $category variable.

Can someone help me?

2
  • Could you show how you used the get_term_by()? because, assuming that the taxonomy is category, get_term_by('slug', $category, 'category') should return the category object, if exists. Sep 13, 2021 at 12:11
  • can you share what you tried with get_term_by?
    – Tom J Nowell
    Sep 13, 2021 at 12:55

2 Answers 2

0

I'm a sucker for regular expressions:

<?php
$category = 'test-category';
$category = preg_replace('/-/', ' ', $category);
$category = ucwords($category); 
echo $category;
1
  • I think OP means that he want the name of the taxonomy, if he indeed only wants to strip dashes and lower case then this is great, but if he want the name of the taxonomy it will not always return the correct result, you can have slug different from name. Sep 13, 2021 at 13:52
0

First, get the term object via get_term_by:

$term = get_term_by( 'slug', 'test-category', 'category' );

Then grab the display name from the term object:

echo esc_html( $term->name );

Note that if it fails to find the term, get_term_by will return false instead, so always check for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.