How to get posts without author?

That won’t be as easy as you’d like to… get_posts uses WP_Query to get posts and if you take a look at WP_Query code, ten you’ll see, that 0 is used as empty in there (https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-includes/class-wp-query.php#L2052):

if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {

It means, that you can’t pass 'author' => 0 and get posts that have 0 as author. And that’s correct behavior, because 0 is not a valid value for post_author column – this column should contain ID of existing user.

On the other hand, if you already have 0s in there, then you’ll have to use custom SQL to get these posts. One way to do this will be with this code:

global $wpdb;
$ids = wp_list_pluck( $wpdb->get_results( "SELECT ID FROM {$wpdb->posts} WHERE post_type=post AND post_author=0" ), 'ID' );
$posts = get_posts( array( 'post__in' => $ids, 'posts_per_page' => -1 ) );

Leave a Comment