Using WordPress ‘get_posts()’ PHP function

The get_posts() WordPress PHP function retrieves an array of the latest posts or posts matching the given criteria.

Usage

get_posts( $args );

Parameters

More information

See WordPress Developer Resources: get_posts()
Implemented in: wp-includes/post.php

Examples

Retrieve the latest 10 posts

This example retrieves the latest 10 posts.

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

Retrieve posts from a specific category

This example retrieves posts from the category with the ID 5.

$args = array(
  'numberposts' => -1,
  'category' => 5,
);
$posts_from_category = get_posts( $args );

Retrieve posts with a specific tag

This example retrieves posts with the tag “travel”.

$args = array(
  'numberposts' => -1,
  'tag' => 'travel',
);
$posts_with_tag = get_posts( $args );

Retrieve posts from a specific author

This example retrieves all posts from the author with the ID 1.

$args = array(
  'numberposts' => -1,
  'author' => 1,
);
$posts_by_author = get_posts( $args );

Retrieve posts with a custom post type

This example retrieves all posts with the custom post type “product”.

$args = array(
  'numberposts' => -1,
  'post_type' => 'product',
);
$custom_posts = get_posts( $args );