I’m trying to set up a list of categories with clickable links to that category.
I’ve looked at:
and am not quite sure where to put the code or how to access it on the page.
I understand the PHP well enough – it’s pretty straightforward, I’m just relatively new to WP and need some help implementing.
I will show you how to display a list of categories in WordPress and also mark the active category, see code below:
Notes about the code above:
get_queried_object() retrieve the currently-queried object. For example:
But there are some implications when using
get_queried_object()
, you should not expect it to return a post type object even when is_post_type_archive() is true. Check it out for more info.Also, note that
get_queried_object()
is a wrapper for$wp_query->get_queried_object()
, so it returns a WP object data type.get_categories()
get_categories() retrieve list of category objects. Currently accepts only one parameter –
$args
. The $args parameter specifies a list of arguments that should be used to retrieve categories. See get_terms() for additional options.However, to get the category for a particular posts here’s a simple function I wrote: How to get list of categories for a post
As per the linked WPSE thread, and the accepted answer, the code is (copied & pasted):
As for us (the WordPress developers) Codex is the key for most of the basics. So according to WordPress Codex:
get_categories()
does query for all the categories of a site, and returns an array.get_posts()
does query for all the posts of a site, and returns an array.And they both are the shortcut of
WP_Query()
. You can get all their possible parameters from the Codex pages. As you are a PHP enthusiast, you know how the code is functioning:$categories
is taking all the categories and for every categoryget_posts()
is taking its posts.So it’s very similar to a mySQL query and a foreach loop in raw PHP. You can put this code into any of your WP site’s active theme’s template pages. Template Hierarchy can give you a detail insight.
As per your title of the Question is:
The answer can be:
I’ve already said, try putting the code into
index.php
,front-page.php
, … anywhere. The key concept is: it’s just a SQL Query and a usefulforeach
loop of PHP.This method enables you to exclude any category simply by adding the cat i.d to the code.
Here’s a better way to add a list of categories conditionally from your child themes functions file in any WordPress or theme specific hook location:
Here’s the result
And here’s the result if you want to use the existing styling from the Twenty Fourteens navigation menus which the above code includes.
The code also enables you to include specific categories or exclude any using the cat i.d’s
You could also create a custom widget area and use the native WordPress category widget.
Simply change the the_content hook to change the location of the categories list.
Modified from this source