Last active
October 16, 2016 08:25
-
-
Save akumaf/d63cdf7510dca8781b64f76560e766eb to your computer and use it in GitHub Desktop.
See http://arevico.com/insert-ignore-queries-in-wordpress-plugins-or-themes/ on how to use this gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* It's possible to modify WordPress insert queries in such a way to ignore duplicates. | |
* Ignoring in this context means that no error is thrown and the insert is skipped. | |
* This can be useful in conjunction with unique keys. When the filter is active, all | |
* calls to $wpdb->insert() are transformed to insert-ignore queries | |
* | |
* Be mindful when running this code in a plugin that you remove the filter when you are done. | |
* It's not nice to edit other people's queries when not necessary. | |
* | |
* @author H.F. Kluitenberg | |
* http://arevico.com/ | |
* | |
*/ | |
class insertIgnore | |
{ | |
/** | |
* Add the IGNORE modifier to an insert query | |
* | |
* @param array $data The data to insert (unescaped) | |
*/ | |
public function insertIgnore( $data ){ | |
global $wpdb; | |
add_filter('query', array($this, 'modifyInsertQuery'), 10); | |
$wpdb->insert( $data ); | |
// Remove our filter again. You can also do this at a later stage | |
remove_filter('query', array($this, 'modifyInsertQuery'), 10); | |
} | |
/** | |
* Modify any incoming queries | |
* | |
* @param string $query The SQL Query | |
* @return string the modified query | |
*/ | |
public function modifyInsertQuery( $query ){ | |
$count = 0; | |
$query = preg_replace('/^(INSERT INTO)/i', 'INSERT IGNORE INTO', $query, 1 , $count ); | |
return $query; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment