Michael Cool Michael Cool - 1 year ago 68
PHP Question

Filter not hooking

I have some difficulties adding a filter from a plugin file.
The filter is applied in an AJAX function.
The plugin file is included correctly, as all the other code is working perfectly.
The other code in the ajax.php file works perfectly.


$user_meta = array(
'lang' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2),
'actkey' => $actkey,
$user_meta = apply_filters( 'add_more_meta', $user_meta, $_POST );
add_user_meta( $user_id, 'data', $user_meta );


function add_more_meta ( $user_meta, $var ) {
$user_meta['major'] = 'major';
return $user_meta;
add_filter( 'add_more_meta', 'add_more_meta', 10, 2 );

The array stays the same and doesn't change.

Anyone got an idea on what I'm doing wrong?

Answer Source

Make sure that your filter is added before the filter tags is applied.

Quick Debug

// Print all filters before `add_more_meta` filter tag applied.
global $wp_filters;

// or check it by has_filter($tag, $function_to_check = false) function.

if(has_filter('add_more_meta', 'add_more_meta') {
var_dump('Yes, filtered');
} else {
var_dump('No, not filtered');

$user_meta = apply_filters( 'add_more_meta', $user_meta, $_POST );

Possible Fix

add_action('init', 'add_my_custom_filters', 10);

function add_my_custom_filters() {
add_filter( 'add_more_meta', 'add_more_meta', 10, 2 );

wrap your custom filters and hook them to init action usually will make sure that the filters work properly in all places included ajax.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download