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?
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?
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/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 ) );