6

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
  • Can you post the code snippet that the sniff is being reported on? Also you can create a custom ruleset to negate this sniff under certain conditions.
    – Adam
    Mar 21, 2015 at 7:26

1 Answer 1

8

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,

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
2
  • 1
    Thank you! Yes, adding the comments fixes it. I assumed it must be okay to do direct DB access at some point. :) Thanks for your help.
    – Sam Wilson
    Mar 25, 2015 at 0:13
  • 1
    The regex for this is /db call\W*(ok|pass|clear|whitelist)/i. See github.com/WordPress-Coding-Standards/…
    – Sam Wilson
    Mar 25, 2015 at 0:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.