Dream. Dare. Do – that is Suyati’s work principle in a nutshell.
The get_posts method:
The very common and appropriate use of this method is to create an array of posts based on given set of parameters. It will fetch a list of recent posts matching this criteria. This method can be used to create Multiple Loops, though a more direct reference.
get_posts method uses WP_Query. get_posts is your best choice in situations where you would like to call an array of posts based on a small set of parameters within a page.
How to Use
Include the below line in your template:
Here we can see the arguments by default:
It returns an Array – List of post objects
Different usages of get_posts method
1. Posts list with an offset:
If your blog configured to show one post per page, but also want to show links to the previous five posts in category ID 1, you can use this way:
Note:This should be used only on a category that has more than one post in it, otherwise there’ll be no output.
2.Fetch all post data:
By default some post-related data is not available to get_posts, such as post content, or the numeric ID. This can be achieved by calling an internal function setup_postdata(), with the $post array as its argument:
Without calling setup_postdata(), you can use $post->COLUMN, where COLUMN is the table column name for the data. So $post->ID holds the ID, $post->post_content the content, and so on. You can use PHPecho command, to print this data.
3. Recent posts ordered by title:
To display the last 10 posts sorted alphabetically in ascending order:
the above will display last 10 posts with their post date and title.
4. Random Display:
Display a list of 10 posts selected randomly:
This done by using the MySQL RAND() function for the order by parameter value.
5. Show all attachments:
This should be carried out outside of any loops.
Here we have just discussed 5 different usages of the get_posts method. We can use this method for many more custom needs For example: fetch posts associated with certain taxonomy, show posts associated with custom field etc.