So I see that get_posts() function return an array of posts.
If there are posts, it returns an array of posts.
If there are no posts it returns an empty array().
If there are posts, but the querying of the database fails (and let's say, 99.999% times it returns correct, but this time it fails for some reason), it returns an empty array. (Important: I'm not sure of this, this is what I understand when I read how this function works).
My question is this: If I use this function, when do I know if the function failed? (Like there are some functions which returns an WP_Error.)
So I see that get_posts() function return an array of posts.
If there are posts, it returns an array of posts.
If there are no posts it returns an empty array().
If there are posts, but the querying of the database fails (and let's say, 99.999% times it returns correct, but this time it fails for some reason), it returns an empty array. (Important: I'm not sure of this, this is what I understand when I read how this function works).
My question is this: If I use this function, when do I know if the function failed? (Like there are some functions which returns an WP_Error.)
Share Improve this question edited Feb 16, 2019 at 10:20 tmdesigned 1,6751 gold badge14 silver badges17 bronze badges asked Feb 16, 2019 at 10:00 BradaBrada 1828 bronze badges 2- What kind of failing do you mean? Like connection error? – Krzysiek Dróżdż Commented Feb 16, 2019 at 10:51
- Hi... I can't say exactly what kind of failing, because I really don't know what can fail, but I think there should be something that can fail. Sure, a connection is very likely to happen if the database is somewhere else... It's just strange that there is nothing to indicate if it's a fail or not, like a lot of other functions that do. Just look at a function like wp_insert_post(), has even a second argument to either return WP_Error on failure or not. – Brada Commented Feb 16, 2019 at 19:17
1 Answer
Reset to default 2Here's one way to check if there was an DB error within get_posts()
:
global $EZSQL_ERROR;
$before = isset( $EZSQL_ERROR ) ? count( $EZSQL_ERROR ) : 0;
$posts = get_posts( $args );
$after = isset( $EZSQL_ERROR ) ? count( $EZSQL_ERROR ) : 0;
if ( empty( $posts ) && $before < $after ) {
// ... DB error(s) within get_posts() when it returns an empty array.
}
Here we check the number of wpdb
errors before and after the get_posts()
call from the global $EZSQL_ERROR
errors collector (src).
But I can imagine that this might give a false positive in some cases though, e.g. if we hook a bad db calls within get_posts()
that might not be the reason for empty posts array.
Update. I tested this and noticed that $wpdb->last_error
is restored after each $wpdb
call. I noticed the global $EZSQL_ERROR
array within wpdb::print_error()
that is not restored but collects the errors. I therefore updated the answer and replaced $wpdb->last_error
with $EZSQL_ERROR
.