插件可能(或者:希望)使用了$wpdb 对象的实例wpdb-类,以添加自定义表。如果是(且仅当是),则其作者可能还使用$wpdb->insert() 将行添加到表中。
查看wpdb::insert(), 看看它source, 你会发现这个方法只是一个方便的包装wpdb::_insert_replace_helper(), 设置$type 参数到INSERT. 虽然此方法没有任何过滤器,但来源显示此函数实际使用
return $this->query( $this->prepare( $sql, $values ) );
而
wpdb::prepare() 不允许通过过滤器进行任何修改,让我们看看
wpdb::query(). 您将在此处找到以下筛选器:
$query = apply_filters( \'query\', $query );
现在我们有了一个可以添加修改的入口点,让我们来讨论如何识别填充了数据的自定义表。查看放入语句中以供执行的SQL语句,您将注意到以下行:
$sql = "$type INTO `$table` ($fields) VALUES ($formats)";
The
$table 变量来自函数定义,函数定义是
$wpdb->insert() 呼叫通常任何sane开发人员都会使用
"{$wpdb->prefix}custom_table_name" 在那里,为了避免在表前缀更改为
wp_ 在…内
wp-config.php.
最后:
<?
/* Plugin Name: Do something when a custom table gets data added or altered */
add_filter( \'query\', function( $query ) {
// Return SQL unmodified. Not the table we are targeting.
if ( false === strstr( $query, "{$wpdb->prefix}custom_table_name" ) ) {
return $query;
}
// Return SQL unmodified. Not the actions we are targeting.
# @TODO If you only want to act on either of them, modify the if-clause
if (
false === strstr( $query, "INSERT" )
AND false === strstr( $query, "REPLACE" )
) {
return $query;
}
# @TODO Do your custom task here and…
# …modify according the query to your likings.
return $query;
} );
请记住,该插件现在可以在每个查询上运行。您可能需要添加如下检查
is_admin() 并将整个代码块包装在一个函数中,该函数附加到一个更专用的挂钩上,以减少它的执行次数。否则,您可能会显著降低站点速度。