Insert Ignore Queries in WordPress Plugins or Themes

There is no doubt that MySQL’s “INSERT IGNORE’ queries are very useful. This allows you to insert rows into a database without using extra queries to check existence and make use of unique indexes without errors. In WordPress plugins or themes this is a little more tricky to do, because you still want to be able to use their database abstraction layer ($wpdb). The $wpdb object does not expose such a function.

In order to achieve this functionality there are 2 routes you can take:

  1. Construct your own SQL queries. Although this is easy to do, your code becomes rather messy. It will be very hard to maintain if you’ve got SQL queries all over the place. The $wpdb object is there for a reason, so use it!
  2. Hook the query filter. This filter runs before WordPress execute a query. I prefer this option, since it is very easy, only requiring a few lines of code and is very robust. In addition, you can sort of toggle behavior. By settings the filter, you can transform insert queries to insert ignore queries and by removing the filter you can disable this behavior.

See the gist below to see how simple it is.