0
0
WordpressHow-ToBeginner · 4 min read

How to Use get_posts in WordPress: Syntax and Examples

Use the get_posts function in WordPress to retrieve an array of posts based on specified criteria by passing an array of arguments. It returns an array of post objects you can loop through to display or process posts.
📐

Syntax

The get_posts function accepts an array of arguments to filter posts. Common arguments include numberposts (how many posts to get), category (category ID), post_type (type of content), and orderby (how to sort posts).

It returns an array of post objects matching the criteria.

php
get_posts(array(
    'numberposts' => 5,
    'category' => 3,
    'orderby' => 'date',
    'order' => 'DESC',
    'post_type' => 'post'
));
💻

Example

This example fetches the 3 latest posts from category ID 2 and displays their titles as a list.

php
<?php
$recent_posts = get_posts(array(
    'numberposts' => 3,
    'category' => 2,
    'orderby' => 'date',
    'order' => 'DESC'
));
echo '<ul>';
foreach ($recent_posts as $post) {
    echo '<li>' . esc_html($post->post_title) . '</li>';
}
echo '</ul>';
?>
Output
<ul><li>Post Title 1</li><li>Post Title 2</li><li>Post Title 3</li></ul>
⚠️

Common Pitfalls

  • Not specifying post_type when you want custom post types, so you get only posts.
  • Using category instead of category_name or cat incorrectly.
  • Not escaping output when displaying post data, which can cause security issues.
  • Expecting get_posts to return WP_Query object; it returns an array of posts instead.
php
<?php
// Wrong: missing post_type for custom post type
$items = get_posts(array('numberposts' => 5));

// Right: specify post_type explicitly
$items = get_posts(array('numberposts' => 5, 'post_type' => 'page'));
?>
📊

Quick Reference

ArgumentDescriptionExample
numberpostsNumber of posts to retrieve'numberposts' => 5
categoryCategory ID to filter posts'category' => 3
post_typeType of post (post, page, custom)'post_type' => 'page'
orderbyField to order posts by'orderby' => 'date'
orderOrder direction ASC or DESC'order' => 'DESC'

Key Takeaways

Use get_posts with an argument array to fetch posts matching your criteria.
Always specify post_type when querying custom post types.
Escape post data before outputting to avoid security risks.
get_posts returns an array of posts, not a WP_Query object.
Use common arguments like numberposts, category, orderby, and order to control results.