I am trying to display the categories name on my page but it’s not displaying. I am using the below code and I added the shortcode gridCategories on my page. I am getting only array
function createGridCategories(){
$categories = get_categories( array(
'taxonomy' => 'category',
'orderby' => 'name',
'parent' => 0,
'hide_empty' => 0, // change to 1 to hide categores not having a single post
) );
var_dump($categories);
return $categories;
}
add_shortcode( 'gridCategories', 'createGridCategories');
I tried this also
$categories = get_the_category(); var_dump($categories);
I added a shortcode like this in textblock

But still, I am not getting any output on my page. Is there any issue with my code?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Is there any issue with my code?
Yes, there is. get_categories() returns an array of terms, e.g. WP_Term objects or a list of term IDs, so you can’t simply do return $categories;.
Instead,
-
For a basic list such as
Foo category, Bar category, etc.(i.e. no category links), you can simply set thefieldsparameter tonameswhich then gives you a list of category names:function createGridCategories() { $categories = get_categories( array( 'fields' => 'names', 'hide_empty' => 0, // other args here ) ); return implode( ', ', $categories ); } -
Or you can manually loop through the terms and just build the markup/HTML to your own liking:
function createGridCategories() { $categories = get_categories( array( 'hide_empty' => 0, // other args here ) ); $list = ''; foreach ( $categories as $term ) { $url = get_category_link( $term ); $list .= '<li><a href="' . esc_url( $url ) . '">' . esc_html( $term->name ) . '</a></li>'; } return "<ul>$list</ul>"; } -
Or alternatively (for a list/
ULlike the above), you can usewp_list_categories():function createGridCategories() { $list = wp_list_categories( array( 'taxonomy' => 'category', 'hide_empty' => 0, 'echo' => 0, 'title_li' => '', // other args here ) ); return "<ul>$list</ul>"; }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0