get_posts – get all posts by author id

The question:

I want to get all posts by certain author id (current user). Later, I want to pick the first post made by this user (ASC).
I guess I do not use the right arguments in get_posts, am I? $current_user_posts
always contains an Array with all blog posts in multiple different WP_Post Objects.

global $current_user;
get_currentuserinfo();                      

$args = array(
    'author'        =>  $current_user->ID, // I could also use $user_ID, right?
    'orderby'       =>  'post_date',
    'order'         =>  'ASC' 
    );

// get his posts 'ASC'
$current_user_posts = get_posts( $args );

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I’m a bit confused. If you want to get onlya element from the posts array you can get it like this:

  • reset($current_user_posts) – first post
  • end($current_user_posts) – lat post

But if you want to get just one post with the get_posts() you can use the posts_per_page argument to limit the results.

$args = array(
    'author'        =>  $current_user->ID,
    'orderby'       =>  'post_date',
    'order'         =>  'ASC',
    'posts_per_page' => 1
    );

More info about parameters you can get on WP Query Class Reference page (get_posts() takes same parameters as WP Query).

Method 2

global $current_user;                     

$args = array(
  'author'        =>  $current_user->ID, 
  'orderby'       =>  'post_date',
  'order'         =>  'ASC',
  'posts_per_page' => -1 // no limit
);


$current_user_posts = get_posts( $args );
$total = count($current_user_posts);

and just loop the current user posts

Method 3

its work by (wp4.9.7)

 $user_id = get_current_user_id();
 $args=array(
 'post_type' => 'POSTTYPE',
 'post_status' => 'publish',
 'posts_per_page' => 1,
 'author' => $user_id
  );

$current_user_posts = get_posts( $args );
$total = count($current_user_posts);
wp_die( '<pre>' .  $total . '</pre>' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment