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 |2 Answers
Reset to default 0I'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)
版权声明:本文标题:php - Get nice name of category from slug (remove dashes of category) 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741323213a2372327.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
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:11get_term_by
? – Tom J Nowell ♦ Commented Sep 13, 2021 at 12:55