I am using a blog to keep track of citations I may want to use for a thesis. Each citation is a Post, authors are categories, which are parents to subcategories that are named for the titles of books or articles by that author. In the description of the book/article subcategories, I put the publishing information, e.g. âPenguin: London, 2007â.
Letâs assume that a particular author category is called âMill, John Stuartâ (for whom there are four citations), the book subcategory âOn Libertyâ (for which there are two citations), and the description âBantam Classic: London, 1993â. Now, I would like to add a Page that shows all the sources that I have gathered, automatically outputting HTML code like this:
<p class="lit-author"><a href="../category/mill-john-stuart/">Mill, John Stuart</a> (4)</p>
<p class="lit-work"><a href="../category/mill-john-stuart/on-liberty/"><i>On Liberty<i></a>. Bantam Classic: London, 1993. (2)</p>
This might just as well be done with <ul>s, Iâm really only interested in being able to format the output using CSS and having in on a Page. (Itâs pretty much just the contents of a Categories widget, but on a Page, plus the category description.)
How would I do this, and where would I have to put the relevant code so that it would be displayed on a specific Page?
(WP 3.2.1, Graphene 1.4.1)
First you need to get all the categories that don’t have parents (top-level categories). We’re going to use
get_terms
for this. Get terms will either return an empty array, aWP_Error
object, or an array of objects representing terms. So we need to make sure our call works before continuing as well.With that in place we can start by outputing a container div, then starting a
foreach
loop to loop through all the categories. We’ll output the term and link inside a paragraph as per your request above.Still inside our
foreach( $cats as $cat )
loop, we can loop for term children. If we find them, we’ll loop through each child, getting its link, name, and description.You can encapsulate this entire mess in a function (note: counts are added here, forgot them above).
And add a shortcode to display it all on any page/post you like.
As a plugin: https://gist.github.com/1196457
Copy
page.php
in your theme root and name itpage-list-of-categories.php
. Put the following at the top:Somewhere after
<?php the_title()?>
place the following…Then make a page and select “Page Category Display” from the dropdown under “Template” in the “Page Attributes” box.
The css classes you have above won’t be output, but you will be able to style them because it appears that your
lit-work
categories are always children of author categories. So you can refer to authors withul#myCategories li
and works asul#myCategories li li
.There are other options — passed in the
$args
array — forwp_list_categories
that you can look into.