Suppose we want to display a list of post links in the sidebar that are in “child” categories of the “News” category (ie “Boating News” followed by its posts, “Fishing News” followed by its posts, in this case from the last 90 days because of the filter). We could include this code in functions.php:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | add_filter('widget_text', 'do_shortcode');//FOR WIDGET SHORTCODE function filter_where($where = '') { //posts in the last 90 days $where .= " AND post_date > '" . date('Y-m-d', strtotime('-90 days')) . "'"; return $where; } function jma_news_posts($atts){ ob_start(); extract( shortcode_atts( array( 'parent_cat_id' => 3, 'number_displayed' => 3, ), $atts ) ); add_filter('posts_where', 'filter_where'); $children = get_categories( array('child_of' => $parent_cat_id) ); foreach ($children as $child) { echo '<h3 class="news-title"><a href="'; echo get_category_link( $child->cat_ID ); echo '">'; echo $child->cat_name; echo '</a></h3>'; $x = new WP_Query('category_name=' . $child->slug . '&posts_per_page=' . $number_displayed); echo '<ul class="news-bar">'; while ( $x->have_posts() ) : $x->the_post(); echo '<li class="sidebar-recent-posts">'; echo '<a class="side-post-title" href="'; the_permalink(); echo '">'; the_title(); echo '</a></li>'; endwhile; echo '</ul>'; } // Reset the global $the_post as this query will have stomped on it wp_reset_postdata(); $x = ob_get_contents(); ob_end_clean(); return $x; } add_shortcode('add_news_with_kids','jma_news_posts'); |
Then in a sidebar text widget we would insert:
0 1 2 | [add_news_with_kids parent_cat_id=3 number_displayed=3] |
This would display all category titles which are children of category with the id of 3, with the 3 newest posts (less than 90 days old) for each category. Of course we could change the category and number displayed by changing the arguments in the shortcode.