Can anyone please tell me how to display my wordpress categories (parents and childs) along with their ids.
i want them printed in this way:
Europe,United Kingdom,London (Europe is a parent category and their childs united kingdom)
10,20,33 (these are their ids)
Europe,France,Paris
10,22,45
Europe,France,Cannes
10,22,49
I tried this code but it didn’t work for me:
<?php
$categories = get_the_category();
$this_cat_ID = $categories[0]->cat_ID;
$this_cat_name = $categories[0]->cat_name;
$this_cat_url = get_category_link($this_cat_ID);
// get the sub category if we have them
foreach ($categories as $cat) {
$parent = $cat->category_parent;
if ($parent != 0 ){
$sub_cat_ID = $cat->cat_ID;
$sub_cat_name = $cat->cat_name;
$sub_cat_url = get_category_link($sub_cat_ID);
}
}
if (!$sub_cat_ID) {
echo $this_cat_ID;
} else {
echo $sub_cat_ID;
}
?>
Your help is very much appreciated thank you
The WordPress function wp_list_categories will return a list of all the categories. If you set the hierarchical flag to true you will get the whole hierarchy. Read the codex article in the link above for details.
There is also a get_categories function that returns an unformatted result. You could use this in your own PHP code.
A third choice is to read the database, there are three tables wp_terms, wp_term_taxonomy and wp_term_relationships that contain the category tree. Here’s the database structure.
Edit: Here’s a shortcode that will produce a listing like that as a nested collection of lists:
To use this add this code to your functions.php and add the shortcode wherever you want it to display:
or you can specify a taxonomy that you want listed
This isn’t the most efficient way to get this result, but it works here. If you started with the hierarchical version of get_categories or used the database you could get a faster version of this.
Where do you want to display this? inside loop? outside? in single.php? category.php? …..?
If you want to display it in a separate place, include first wp-load.php, like this
What i want to do is this:
The steps I Followed (please check this link)
I only want to change this code:
so that the list of of all the categories and their childs will be displayed along with their ids in this format:
Example:
Europe,United Kingdom,London, East Ham : 25,28,34,36
this is just one parent category (Europe) and its childs (Uk)
the child of UK is London, and the child of london is East Ham.
25 is the id of Europe, 28 is the id of UK, 34 is the id of London, 36 is the id of East Ham
Please note: I just want to display this list on a page as described in the link above.
Thank you so much