Yogesh Chauhan's Blog

WordPress get_posts Examples

in WordPress on February 24, 2021

We know how we can use get_posts to get the latest posts. Now, let’s explore some more examples.

Get the latest 10 posts


$args = array(
  'numberposts' => 10
);
 
$latest_posts = get_posts( $args );

Get the latest 10 posts from custom post type


$args = array(
  'numberposts' => 10,
  'post_type'   => 'events'

);
 
$latest_posts = get_posts( $args );

Set the return values to ids instead of post objects


$args = array('fields' => 'ids');
$posts = get_posts($args);

Access all post data

Some post-related data is not available to get_posts by default, such as post content through the_content(), or the numeric ID.

This is resolved by calling an internal function setup_postdata(), with the $post array as its argument:


$lastposts = get_posts( array(
    'posts_per_page' => 3
) );
 
if ( $lastposts ) {
    foreach ( $lastposts as $post ) :
        setup_postdata( $post ); ?>
        //do something with the_permalink(); the_title() and the_content(); 
    endforeach; 
    wp_reset_postdata();
}

To access a post’s ID or content without calling setup_postdata(), or in fact any post-specific data, we 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.

Custom Field Parameters

Use meta_query to retrieve the meta keys from custom post type.


$args = array(
    'post_type'  => 'product',
    'meta_query' => array(
        array(
            'key'   => 'featured',
            'value' => 'yes',
        )
    )
);
$postslist = get_posts( $args );

Taxonomy Parameters

We can show posts associated with certain taxonomy.

If specifying a taxonomy registered to a custom post type then instead of using ‘category’ we would use custom_taxonomy_name.

For example, if we had a custom taxonomy called “genre” and wanted to only show posts from the “jazz” genre you would use the below code.


$show_albums = get_posts( array(
     'posts_per_page' => 8,
     'orderby'        => 'rand',
     'post_type'      => 'albums',
     'genre'          => 'jazz',
     'post_status'    => 'publish'
) );

We can also use tax_query


$args = array(
    'tax_query' => array(
        array(
            'taxonomy' => 'genre',
            'field'    => 'slug',
            'terms'    => 'jazz'
        )
    )
);
$postslist = get_posts( $args );

Get a post ID by its slug

Use meta_query to retrieve the meta keys from custom post type.



$the_slug = 'my-slug';
$args=array(
    'name'           => $the_slug,
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => 1
);
$my_posts = get_posts( $args );
 
if ( $my_posts ) {
    printf( __( 'ID on the first post found %s', 'textdomain' ), esc_html( $my_posts[0]->ID ) );
}


Get posts in the specified order with include


$posts = get_posts( array(
    'include'   => '3,8,1,17',
    'post_type' => 'attachment',
    'orderby'   => 'post__in',
) );

Show all attachments


$attachments = get_posts( array(
    'post_type'      => 'attachment',
    'posts_per_page' => 500,
    'post_status'    => 'any',
    'post_parent'    => null
) );
 
if ( $attachments ) {
    foreach ( $attachments as $post ) {
        setup_postdata( $post );
        the_title();
        the_attachment_link( $post->ID, false );
        the_excerpt();
    }
    wp_reset_postdata();
}

Get all published posts of all post types


$posts = get_posts( array(
  'post_type' => get_post_types(),
  'post_status' => 'publish',
  'numberposts' => -1,
) );

Get latest posts ordered by title


$postslist = get_posts( array(
    'posts_per_page' => 10,
    'order'          => 'ASC',
    'orderby'        => 'title'
) );

Get 5 random posts

We can display a list of posts selected randomly by using the MySQL RAND() function for the orderby parameter value. Let’s display 5 random posts.


$rand_posts = get_posts( array(
        'posts_per_page' => 5,
        'orderby'        => 'rand'
    ) );

Group and order results by post types names


$args = array(
  'posts_per_page' => 10,
  'post_type'      => array('page','post'),
  'post_status'    => 'publish',
  'offset'     => 0,
  's'          => 'Lorem',
  'orderby'        => 'post_type',
  'order'          => 'ASC'
);

$posts = get_posts( $args );

Show attachments for the current post


$attachments = get_posts( array(
    'post_type'      => 'attachment',
    'posts_per_page' => -1,
    'post_status'    => 'any',
    'post_parent'    => $post->ID
) );
 
if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        echo apply_filters( 'the_title' , $attachment->post_title );
        the_attachment_link( $attachment->ID , false );
    }
}

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
The Sort and Compare Functions in JavaScriptJavaScriptHow to get Current Year, Month and Date in JavaScript?JavaScriptHow Do You Make a Private VPN?MiscellaneousHow to modify AutoSave Interval using code in WordPress?WordPressIntroduction to components and templates Part 3: Data bindingAngularThe difference between Class declarations and Class expressions in JavaScriptJavaScript