The default widget that display recent post on wordpress displays all the posts. But if for ecample you use posts to display products, and posts to display news, they will show in the recent post side by side. Sometimes you even don’t want those special posts to be displayed at all.
You should already know that you can overridethe defaults widgets by redeclaring the widget in your function.php file. So here is a quick way to display only posts from one category (and all her childrens) with the recent post widget.
Copy this function to your the file function.php in your template folder. If you haven’t got one create a blank one and paste the code in.
if ( ‘%BEG_OF_TITLE%’ != $args[‘before_title’] ) {
if ( $output = wp_cache_get(‘widget_recent_entries’, ‘widget’) )
return print($output);
ob_start();
}
extract($args);
$options = get_option(‘widget_recent_entries’);
$title = empty($options[‘title’]) ? __(‘Recent Posts’) : apply_filters(‘widget_title’, $options[‘title’]);
if ( !$number = (int) $options[‘number’] )
$number = 10;
else if ( $number < 1 )
$number = 1;
else if ( $number > 15 )
$number = 15;
global $post;
$r = new WP_Query(array(’showposts’ => $number, ‘category_name’ => ‘news’, ‘what_to_show’ => ‘posts’, ‘nopaging’ => 0, ‘post_status’ => ‘publish’));
if ($r->have_posts()) :
?>
<?php echo $before_widget; ?>
<?php echo $before_title . $title . $after_title; ?>
<ul>
<?php while ($r->have_posts()) : $r->the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?> </a></li>
<?php endwhile; ?>
</ul>
<?php echo $after_widget; ?>
<?php
wp_reset_query(); // Restore global post data stomped by the_post().
endif;
if ( ‘%BEG_OF_TITLE%’ != $args[‘before_title’] )
wp_cache_add(‘widget_recent_entries’, ob_get_flush(), ‘widget’);
}
wp_register_sidebar_widget(‘recent-posts’, __(‘Recent Posts’), ‘wp_widget_recent_entries_news’, ”);
The name of the function is different because in php you can’t declare two functions with the same name. The rest of the code if exactly the same as the default widget exept for the WP_Query parameters. Here I’ve added a parameter called ‘category_name’ equal to the name of the category I want to display. Simple!
Note: if you copy the code from this page you will need to replace all quotes by the proper ‘ quote because the plugin I use at the moment to display code change them into quotes that are not correct in php code.
Related Items and Services:do you need Pop-up Displays for your business












Comments