YogeshChauhan . com

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

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to Write Complex Search Queries in SQL?SQL/MySQLFull and Partial CUBE in Postgres with ExamplesPostgresSolution to pod install fails with json error on Mac OS X 10.15 (or Mac OS Catalina)MiscHow to create an empty array in Swift?SwiftDISTINCT ON: The confusing, unique and useful feature in PostgresPostgresEXISTS and NOT EXISTS in PostgresPostgres