Yogesh Chauhan's Blog

How to modify the latest post array using get_posts() in WordPress?

in WordPress on February 24, 2021

We know that we can use get_posts() to retrieve recent posts from WordPress. The function accepts parameters but if you don’t pass any then it will use the default values for those parameters and return the recent posts in default WordPress post type.

The most appropriate use for get_posts is to create an array of posts based on a set of parameters. It retrieves a list of recent posts or posts matching this criteria.

get_posts can also be used to create Multiple Loops using WP_Query.

👉 The parameters of get_posts are similar to those of get_pages but are implemented differently. get_posts uses WP_Query, whereas get_pages queries the database more directly.

get_posts does not affect or alter the main loop because it references a new WP_Query object.

If you would like to alter the main query before it is executed, you can hook into it using pre_get_posts.

If you would just like to call an array of posts based on a small and simple set of parameters within a page, then get_posts is your best option.

The syntax is like this:


get_posts($args)

Where $args is an arguments array we can pass to retrieve posts.

👉 It is optional. So that makes the default value null.

👉 It returns an array of post objects or post IDs.

Some of the values we can pass are:

numberposts: It’s an int parameter to get total number of posts. If you want all posts then pass it as -1. The default value is 5.

category: We can pass category parameter as in Category ID or comma-separated list of IDs. It can be an int or a string. Default is 0.

include: With this parameter we can pass the an array of post IDs to retrieve. It’s going to include sticky posts as well. It will return an array.
Default value for this parameter is an empty array.

exclude: This parameter is the opposite of the include parameter we saw previously. With this parameter we can pass an array of post IDs not to retrieve. By default the value will be an empty array.

suppress_filters: It take a boolean value and we can notify whether to suppress filters. Default value is true.

Examples

This is how the function looks like with the defaults


function get_posts( $args = null ) {
    $defaults = array(
        'numberposts'      => 5,
        'category'         => 0,
        'orderby'          => 'date',
        'order'            => 'DESC',
        'include'          => array(),
        'exclude'          => array(),
        'meta_key'         => '',
        'meta_value'       => '',
        'post_type'        => 'post',
        'suppress_filters' => true,
    );
    ...
    ...
    $get_posts = new WP_Query;
    return $get_posts->query( $parsed_args );
 
}

Add your values in this WP_Post object


WP_Post Object
(
    [ID] =>
    [post_author] =>
    [post_date] => 
    [post_date_gmt] => 
    [post_content] => 
    [post_title] => 
    [post_excerpt] => 
    [post_status] =>
    [comment_status] =>
    [ping_status] => 
    [post_password] => 
    [post_name] =>
    [to_ping] => 
    [pinged] => 
    [post_modified] => 
    [post_modified_gmt] =>
    [post_content_filtered] => 
    [post_parent] => 
    [guid] => 
    [menu_order] =>
    [post_type] =>
    [post_mime_type] => 
    [comment_count] =>
    [filter] =>
)

Get 15 posts in return instead of the default 5


$args = array(
  'numberposts' => 15
);
 
$latest_posts = get_posts( $args );
//do something with retrieved posts

Get 15 posts in return instead of the default 5 with custom post type


$args = array(
  'numberposts' => 15,
  'post_type'   => 'events'
);
 
$latest_posts = get_posts( $args );
//do something with retrieved posts

Credit goes to this WP Page


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Full and Partial ROLLUP in Postgresql with ExamplesPostgresAt-rules: @error and @warn in SCSSSCSSHow to use images instead of HTML radio buttons using CSS?CSSThe 7 Security Objectives of Any Organization for IT and Network SecurityMiscellaneousWP_Query Class in WordPressWordPressWhat Does Host-Based Intrusion Detection System (HIDS) Mean and What Are Some Advantages Over NIDS?Miscellaneous