Get all posts by post_author

I am creating a back-end dashboard where I need to show all the post assigned to current user by the wp admin.

I assign user role to Author and while creating post (as a wp
admin) just assign this post to some author from Author drop-down.

Read More

So I need to show posts with status Publish. I am now using simple query post but it is returning all posts.

global $current_user;
get_currentuserinfo();
$user_id = $current_user->ID;    // for current user it is 2

$query = array(
        'post_type' => 'post',
        'post_author' => $user_id,
        'post_status' => array('publish')
    );
$my_posts = query_posts($query);

I also hard-coded post_author to 2

I also tried $my_post = new WP_Query(array( 'post_author' => '2' ));

but fail.

Related posts

Leave a Reply

3 comments

  1. Thanks to [Sheikh Heera][1]

    if ( is_user_logged_in() ):
        global $current_user;
        get_currentuserinfo();
        $author_query = array(
            'posts_per_page' => '-1',
            'author' => $current_user->ID
        );
        $author_posts = new WP_Query($author_query);
        while($author_posts->have_posts()) : $author_posts->the_post();
    ?>
            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
    <?php           
        endwhile;
    else :
    
        echo "not logged in";
    endif;
    
    
      [1]: https://stackoverflow.com/users/741747/sheikh-heera
    
  2. The following mini-plugin adds a dashboard widget that queries posts from the current user that have publish as post status. You can see get_current_user_id() in use.

    <?php
    defined( 'ABSPATH' ) OR exit;
    /**
     * Plugin Name: (#91605) Dashboard Widget - User posts
     */
    
    add_action( 'wp_dashboard_setup', 'wpse91605_dbwidget_user_posts' );
    function wpse91605_dbwidget_user_posts()
    {
        wp_add_dashboard_widget(
             'wpse91605_dbwidget_user_posts'
            ,_e( 'Your published posts', 'your_textdomain' )
            ,'wpse91605_dbwidget_user_posts_cb'
        );
    }
    function wpse91605_dbwidget_user_posts_cb()
    {
        $query = new WP_Query( array(
             'author'         => get_current_user_id()
            ,'post_status'    => 'publish'
            ,'posts_per_page' => -1
            ,'showposts'      => -1
            ,'nopaging'       => true
        ) );
        if ( $query->have_posts() )
        {
            ?><ul><?php
            while( $query->have_posts )
            {
                the_post();
                ?>
                <li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                </a></li>
                <?php
            }
            ?></ul><?php
        }
    }