A friend of mine asked me to write a Wordpress function the other day that printed out a list of categories and any posts in those categories, along with any meta data that might be in the post.
All the function does is to get a list of categories and then for each category get a list of the posts associated with that category. Not much really, but useful in some circumstances.
function getCategoryPostList($args = array())
{
if (is_string($args)) {
parse_str($args, $args);
}
// Set up defaults.
$defaults = array(
'echo' => true,
);
// Merge the defaults with the parameters.
$options = array_merge($defaults, (array)$args);
$output = '';
// Get top level categories
$categories = get_categories(array('hierarchical' => 0));
// Loop through the categories found.
foreach ($categories as $cat) {
// Print out category name
$output .= '<p><strong>' . $cat->name . '</strong></p>';
// Get posts associated with the category
$tmpPosts = get_posts('category=' . $cat->cat_ID);
// Make sure some posts were found.
if (count($tmpPosts) > 0) {
$output .= '<div>';
// Loop through each post found.
foreach ($tmpPosts as $post) {
// Get post meta data.
setup_postdata($post);
// Print out post information
$output .= '<p><a href="' . get_page_link($post->ID) . '" title="' . $post->post_title . '">' . $post->post_title . '</a></p>';
$output .= '<p>' . $post->post_excerpt . '</p>';
}
$output .= '</div>';
}
}
if ($options['echo'] == true) {
// Print out the $output variable.
echo $output;
}
// Return
return $output;
}
To use the function pop it into your functions.php file and call it in your theme like this:
getCategoryPostList();
This will probably work best if you create a custom page template and put the function call in there.
The only problem with this function is that if you have a post in multiple categories then you will find the post appearing multiple times. This wasn't an issue for the person I wrote it for, but if you want to change this and think of a good way to do it then post a comment!
Comments
This function is awesome, thanks so much!
Note to others: this function will not automatically include posts from a custom post type, but you can add that like so:
$tmpPosts = get_posts('post_type=whatever&category=' . $cat->cat_ID);
Perhaps there's a more elegant option, but that worked for me! Hope it helps somebody.
Your script works nice in normal categories :) but its not work with custom post type taxonomies i change this line
<code>$tmpPosts = get_posts('post_type=headline&category=' . $cat->cat_ID);</code>
But no categories shows :(