admin管理员组

文章数量:1287973

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?

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?

Share Improve this question asked Sep 13, 2021 at 11:51 JohanJohan 3091 gold badge10 silver badges19 bronze badges 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. – Buttered_Toast Commented Sep 13, 2021 at 12:11
  • can you share what you tried with get_term_by? – Tom J Nowell Commented Sep 13, 2021 at 12:55
Add a comment  | 

2 Answers 2

Reset to default 0

I'm a sucker for regular expressions:

<?php
$category = 'test-category';
$category = preg_replace('/-/', ' ', $category);
$category = ucwords($category); 
echo $category;

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.

本文标签: phpGet nice name of category from slug (remove dashes of category)