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.

Was it helpful?

Solution

The close() function was added for completeness in the database abstraction. If the database is prematurely closed in a plugin or theme (as you are using it), the next call to wpdb::query() will re-open the connection.

Your Commands out of sync error is a MySQL error, not a WordPress one, and it might be coming from a plugin or theme that you're using. Googling for wordpress database commands out of sync comes up with a lot of possible issues, including caching plugins. Try disabling all plugins and switching to a default theme (like Twenty Twenty); if the issue goes away, turn plugins back on till you find the culprit. Then contact that plugin's support crew.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top