Get user posts with custom WP_Query on author.php

The question:

I try to show custom post list with WP_Query on author.php like this:

    <?php $args = array( 'post_type' => 'post', 'author' => 'get_queried_object_id()', 'posts_per_page' => 9 );
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        
<figure><a href="<?php the_permalink(); ?>"><img src="<?php if ( has_post_thumbnail() ) : the_post_thumbnail(); endif; ?>" alt="<?php the_title(); ?>"></a></figure>
<h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>

                
        <?php endwhile; wp_reset_postdata(); ?>
        
        <?php else : ?>
        <p><?php _e( 'No posts by this author' ); ?></p>
    <?php endif; ?>

It gives posts from all authors for some reason. I’ve tried different combinations of ‘author’ array element with no luck or some other errors/issues (like displaying only one post for example).

Please help to solve this issue.

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

Functions in single quotes will be interpret as string.
You just need to remove single quotes in your $args array.

$args = array( 
    'post_type' => 'post', 
    'author' => get_queried_object_id(), //remove single quotes here
    'posts_per_page' => 9 
);


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