Advertisement
stevejohnson

Posts by categories

Oct 18th, 2012
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.43 KB | None | 0 0
  1. <?php
  2.     /** Start copy/paste */
  3.     /**
  4.      * this function does all the work:
  5.      * asks for a list of categories
  6.      * if that is successful,
  7.      * retrieves the posts associated with
  8.      * each category
  9.      */
  10.     function list_posts_by_cat() {
  11.         $taxonomy = 'category';
  12.         $param_type = 'category__in';
  13.         $term_args = array(
  14.             'orderby' => 'name',
  15.             'order' => 'ASC'
  16.         );
  17.         $terms = get_terms( $taxonomy, $term_args );
  18.        
  19.         $list = '';
  20.         if ( $terms ) {
  21.             foreach( $terms as $term ) {
  22.                 $qargs = array(
  23.                     "$param_type" => array( $term->term_id ),
  24.                     'post_type' => 'post',
  25.                     'post_status' => 'publish',
  26.                     'posts_per_page' => -1,
  27.                     'caller_get_posts'=> 1
  28.                 );
  29.                 $new_posts = null;
  30.                 $new_posts = new WP_Query( $qargs );
  31.                
  32.                 if( $new_posts->have_posts() ) {
  33.                     $list .= "<div class='post-list-by-cat'>" . PHP_EOL;
  34.                     $list .= "\t<h4>List of Posts in $taxonomy $term->name</h4>" . PHP_EOL;
  35.                     $list .= "\t<ul>" . PHP_EOL;
  36.                     while ( $new_posts->have_posts() ) :
  37.                         $new_posts->the_post();
  38.                         $list .= "\t\t<li><a href='" . get_permalink() . "' rel='bookmark' title='Permanent Link to " . the_title_attribute( 'echo=0' ) . "'>" . get_the_title() . "</a></li>" . PHP_EOL;
  39.                     endwhile;
  40.                     $list .= "\t</ul>" . PHP_EOL;
  41.                     $list .= "</div>" . PHP_EOL;
  42.                 }
  43.             }
  44.             return $list;
  45.         }
  46.         wp_reset_query();
  47.     }
  48.     add_shortcode( 'listposts', 'list_posts_by_cat' );
  49.     /** END copy/paste */
  50. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement