Skip to content

Instantly share code, notes, and snippets.

@tenman
Created May 16, 2014 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tenman/f8029ef87a5043946315 to your computer and use it in GitHub Desktop.
Save tenman/f8029ef87a5043946315 to your computer and use it in GitHub Desktop.
recent posts each categories
<?php
/* カテゴリIDをキーとした配列の作成 */
$category_ids = array_flip( get_all_category_ids() );
$category_ids = array_map( "reset_val", $category_ids );
/* 表示する投稿の件数(最大) */
$limit_posts = 5;
function reset_val( $str ) {
return 0;
}
query_posts( array( 'posts_per_page' => -1 ) );
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
$categories = get_the_category();
//var_dump( $categories);
//echo '<hr />'
/* 一つ目のループでは、カテゴリIDをキーにした配列に、投稿IDをセット */
foreach ( $categories as $key => $val ) {
if ( empty( $result[ $val -> term_id ] ) || count( $result[ $val -> term_id ] ) < $limit_posts ) {
$result[$val -> term_id][ $post -> ID] = $post -> ID;
}
}
}
}
wp_reset_query();
/* このループで、htmlを組み立てて表示 */
echo '<ul>';
foreach ( $result as $key => $vals ) {
$category_link = '<li><h3><a href="%1$s" title="Category Name">%2$s</a></h3><ul>';
printf( $category_link, get_category_link( $key ), get_cat_name( $key ) );
$entry_html = '<li><span>%2$s</span> <a href="%1$s">%3$s</a>';
foreach ( $vals as $val ) {
$permalink = get_permalink( $val );
$date = get_the_time( 'Y m d', $val );
$title = get_the_title( $val );
printf( $entry_html, $permalink, $date, $title );
}
echo '</li></ul></li>';
}
echo '</ul>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment