2

I am looking for a way to get all posts without author.

They were inserted with post_author = 0;

But the following line returns all posts instead of the posts with no/null author

get_posts( array('author' => 0 ));

How to get posts without author?

1 Answer 1

4

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 ) );
1
  • Thanks for the answer I will try this. I need to check if the value is 0 or if there is no value at all. Anyways an 'author_query' array like for meta and taxonomies would be very useful to compare authors with EXISTS, NOT EXISTS, >, <, IN
    – RafaSashi
    Commented Feb 26, 2019 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.