WordPress widget to display posts from specific category

Open functions.php file in your current theme. Copy the below-given code in the functions.php file of your theme.


// add our shortcode
add_shortcode('pk_get_posts', 'pk_get_posts');

function pk_get_posts( $atts ) {
	global $post;
	$str = '';

	extract( shortcode_atts( array(
		'numberposts' => '5',
		'offset' => '',
		'category' => '',
		'order' => 'DESC',
		'include' => '',
		'exclude' => '',
		'meta_key' => '',
		'meta_value' => '',
		'post_type' => 'post',
		'post_mime_type' => '',
		'post_parent' => '',
		'post_status' => 'publish',
	), $atts ) );

	$args = array(
		'numberposts'     => $numberposts,
		'offset'          => $offset,
		'category'        => $category,
		'orderby'         => $orderby,
		'order'           => $order,
		'include'         => $include,
		'exclude'         => $exclude,
		'meta_key'        => $meta_key,
		'meta_value'      => $meta_value,
		'post_type'       => $post_type,
		'post_mime_type'  => $post_mime_type,
		'post_parent'     => $post_parent,
		'post_status'     => $post_status
	);
	$postslist = get_posts( $args );

	$str = '


<div class="recent-article-box">
';
		$str .= '


<ul class="recent-article">';
			foreach( $postslist as $post ) :
				setup_postdata($post);
				$str .= '


<li><a href="'. get_permalink( $post->ID ) .'" title="'. $post->post_title .'">'. $post->post_title .'</a></li>



';
			endforeach;
		$str .= '</ul>



';
	$str .= '</div>



';
	wp_reset_query();

	return $str;
}

We use wp_reset_query() functions to destroy the previous query used on a custom loop.

How to use the shortcode?

Put [pk_get_posts] in your post, pages or text widget.

Note: The category parameter needs to be the ID of the category, and not the category name.

That displays all posts in all categories, to limit post display on specific category only, add category parameter.


[pk_get_posts category="5"]
// where 5 is the category ID

To limit post display use numberposts parameter.


[pk_get_posts numberposts="15" category="5"]
// where 15 is the number of posts to display.
// where 5 is the category ID

To add more parameters use parameters I’ve listed above.

If the shortcode didn’t work in the text widget, don’t worry.

Add this short snippet in functions.php of your theme.


add_filter( 'widget_text', 'do_shortcode' );

Leave a Reply