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 thefields
parameter tonames
which 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/
UL
like 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>"; }