WordPress-Coding-Standards reports that “Usage of a direct database call is discouraged.”

It’s complaining about my usage of $wpdb->insert() in a plugin. Is this not recommended? What is the correct way to insert data into a plugin’s database table?

Or can I just ignore this error? In which case, is there some system to mark it as reviewed and not to be flagged again?

1
1

Using $wpdb->insert and or related methods to modify data within any of the default WordPress tables, be it posts, postmeta, user, usermeta etc is discouraged because there are functions which already exist for the purpose of modififying data within those tables.

For example,

  • wp_insert_post
  • wp_update_post
  • wp_delete_post

Database Queries

Avoid touching the database directly. If there is a defined function that can get the data you need, use it. Database abstraction (using functions instead of queries) helps keep your code forward-compatible and, in cases where results are cached in memory, it can be many times faster.

https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#database-queries

However it is acceptable to use the wpdb class on custom tables for which no function wrappers exist for the purpose in which you need.

You can try adding a comment on the line of the query:

$wpdb->insert() //db call ok
$wpdb->insert() //db call ok; no-cache ok

Leave a Reply

Your email address will not be published. Required fields are marked *