Should close $wpdb via $wpdb->close()

Question

I’ve been writing a few custom plugins for my site and I was wondering about the correct way to interact with $wpdb.
My plugin executes a few queries using the global $wpdb connection.
I noticed that a $wpdb->close(); method has been added to WordPress, to close the database connection object.

My question is: Should a plugin close out the connection after executing queries?

I have been searched on the folder of some famous plugin(like rank math, Yoast). they use $wpdb a lot but I could not find $wpdb->close() on their code. I mean at the end of their function they do not close query.

for example, I have been writing a function for counting post from last week

    function get_posts_count_from_last_week($post_type = 'post')
 {
        global $wpdb;
        $numposts = $wpdb->get_var($wpdb->prepare("SELECT COUNT(ID) " . "FROM " . $wpdb->posts . " WHERE post_status='publish' AND post_type= %s AND post_date> %s", $post_type, date('Y-m-d H:i:s', strtotime('-168 hours'))));
        return $numposts;

}

I get a lot of “WordPress database error Commands out of sync; you can’t run this command now for query SELECT”
So I have to put $wpdb->close(); before return and after that I did not get Commands out of sync at all.

I confuse, why I have to close the connection when other plugins don’t do that!
by the way in my theme I have some functions with global $wpdb but, again there is not any $wpdb->close() for closing.

0
D.JCode 4 months 2020-12-20T19:10:34-05:00 0 Answers 9 views 0

Leave an answer

Browse
Browse