Blog / WordPress/ How to Get a List of Posts by a Specific User ID in WordPress

How to Get a List of Posts by a Specific User ID in WordPress

WordPress 如何获取指定用户ID的文章列表?

Introduction

When developing WordPress themes or plugins, you may need to retrieve a list of posts published by a specific user. While some might consider get_post(), this function is designed for fetching a single post's details, not a list. To get posts by a user, you should use WP_Query or get_posts().

Core Method: Using WP_Query

WP_Query is WordPress's most powerful and flexible post query class. By setting the author parameter, you can easily retrieve posts by a specific author (user).

Basic Usage Example

<?php
$args = array(
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'author'         => 1,
    'posts_per_page' => 10,
    'orderby'        => 'date',
    'order'          => 'DESC',
);

$user_posts_query = new WP_Query( $args );

if ( $user_posts_query->have_posts() ) {
    echo '<ul>';
    while ( $user_posts_query->have_posts() ) {
        $user_posts_query->the_post();
        echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
    }
    echo '</ul>';
    wp_reset_postdata();
} else {
    echo 'No posts found for this user.';
}
?>

Key Parameters

  • author: The core parameter specifying the user ID. Accepts a single integer or an array of IDs.
  • post_type: Defaults to 'post'. Change this for custom post types.
  • post_status: Defaults to 'publish'. Can be 'draft', 'private', etc.
  • posts_per_page: Controls the number of posts returned.

Alternative Method: Using get_posts()

get_posts() is a simplified wrapper for WP_Query that directly returns an array of post objects, suitable for simple queries.

<?php
$args = array(
    'author'         => 1,
    'posts_per_page' => 5,
);

$user_posts = get_posts( $args );

if ( $user_posts ) {
    foreach ( $user_posts as $post ) {
        setup_postdata( $post );
        echo '<h3><a href="' . get_permalink( $post->ID ) . '">' . $post->post_title . '</a></h3>';
    }
    wp_reset_postdata();
}
?>

Common Issues and Notes

  • Getting the User ID: Typically obtained from get_current_user_id() (current logged-in user) or a user object.
  • Performance: For complex lists (e.g., with pagination, category filters), use WP_Query for better control.
  • Data Reset: Always call wp_reset_postdata() after custom queries with WP_Query or get_posts() to restore the main loop's global $post data.

Using these methods, you can flexibly and efficiently retrieve and display a list of posts by a specific user in WordPress.

Post a Comment

Your email will not be published. Required fields are marked with *.