WORDPRESS – DISPLAY POSTS IN THE SIDEBAR ON SPECIFIC CATEGORY ONLY

0 99

 

Last few days, a friend of mine ask me to create wordpress tutorial to display posts in the sidebar on specific category only and I want to share you how easy to make it in wordpress using shortcode, you know already shortcode right? Well, you should, shortcode is a simple set of functions for creating macro codes for use in post content.

Ok, let’s start.

In this tutorial we’re going to use get_posts() functions.

get_posts()

This is a simple function for creating multiple loops. It retrieves a list of latest posts or posts matching criteria.

Syntax

Parameters

This functions use same parameters as WP_Query does, see below a few of those.

  • numberposts: The number of post to return.
  • category: The category ID where to get the list of posts.
  • orderby: Post field used to sort posts.
  • order: How to sort $orderby
    • ASC
    • DESC
  • include: Post ID to include separated by comma.
  • exclude: Post ID to exlode separated by comma.
  • post_type: Post type to return, default ‘post’.
  • post_status: Post status to return.
    • hold
    • approve
    • spam
    • trash

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

Ok, let’s start coding

Open functions.php file in your current theme or if you don’t have one, please create functions.php file and copy and paste the code below.

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

How to use the shortcode?

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

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

To limit post display use numberposts parameter.

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

Troubleshooting

If the shortcode didn’t work in the text widget, don’t worry folks I’ve a solution on it.

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

Don’t want to get your hands dirty?

Not a problem folks here is the plugin from other developer Category Posts Widget.

That’s it happy coding.

You might also like More from author

Leave A Reply

Your email address will not be published.