Created
September 6, 2011 02:50
-
-
Save chrisguitarguy/1196457 to your computer and use it in GitHub Desktop.
Custom category list display for WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Get Terms Example | |
Plugin URI: http://pmg.co | |
Description: Get a list of all the categories and format them pretty like for output | |
Version: n/a | |
Author: Christopher Davis | |
Author URI: http://pmg.co/people/chris | |
License: Creative Commons/GPL2 | |
*/ | |
add_action( 'init', 'wpse25157_init' ); | |
function wpse25157_init() | |
{ | |
add_shortcode( 'ref-list', 'wpse25157_ref_list' ); | |
} | |
function wpse25157_ref_list() | |
{ | |
// very hackish get_terms call with the 0 as a string to return top level terms | |
$cats = get_terms( 'category', array( 'parent' => '0' ) ); | |
if( ! $cats || is_wp_error( $cats ) ) return; | |
$out = '<div id="ref-list">' . "\n"; | |
foreach( $cats as $cat ) | |
{ | |
$out .= sprintf( | |
'<p class="lit-author"><a href="%s">%s</a> (%s)</p>', | |
esc_url( get_term_link( $cat ) ), | |
sanitize_term_field( 'name', $cat->name, $cat->term_id, 'category', 'display' ), | |
sanitize_term_field( 'count', $cat->count, $cat->term_id, 'category', 'display' ) | |
); | |
$out .= "\n"; // add some newlines to prettify our source | |
$children = get_term_children( $cat->term_id, 'category' ); | |
if( $children && ! is_wp_error( $children ) ) | |
{ | |
foreach( $children as $child ) | |
{ | |
$child = get_term( $child, 'category' ); | |
if( is_wp_error( $child ) ) continue; | |
$out .= sprintf( | |
'<p class="lit-work"><a href="%s"><em>%s</em></a>. %s (%s)</p>', | |
esc_url( get_term_link( $child ) ), | |
sanitize_term_field( 'name', $child->name, $child->term_id, 'category', 'display' ), | |
esc_attr( $child->description ), | |
sanitize_term_field( 'count', $child->count, $child->term_id, 'category', 'display' ) | |
); | |
$out .= "\n"; // prettifying newline | |
} | |
} | |
} // end of the foreach( $cats as $cat ) loop | |
$out .= "</div>\n"; | |
return $out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment