0

I've added an element to a menu with php (code simplified for illustrational purposes):

add_filter( 'wp_nav_menu_' . $menu_slug . '_items', 'add_menu_item' , 10, 2 );
function add_menu_item ( $items ) {
    $item = sprintf('<li class="custom-item">%s</li>', menu_item_content () );
    $items .= $item;
    return $item;
}
function menu_item_content () {
    $item_content = rand(1,99).' custom menu item';
    $item_content = apply_filters( 'custom_menu_item_filter', $item_content );
    return $item_content;
}

I update this very same element via ajax when a button is pressed:

php:

add_action( 'wp_ajax_menu_item_ajax', array( &$this, 'menu_item_ajax' ), 0 );
add_action( 'wp_ajax_nopriv_menu_item_ajax', array( &$this, 'menu_item_ajax' ), 0 );   
function menu_item_ajax() {
    echo menu_item_content ();
    die();
}

js:

$('.custom-item').load(menu_item_ajax.ajaxurl+'?action=menu_item_ajax&_wpnonce='+menu_item_ajax.nonce);

This works fine on my dev site. The menu item is updated and a custom filter (custom_menu_item_filter) is properly applied.

However, on another site (different theme, plugins etc.), the menu item is updated when a button is pressed, but the filter is never applied.

Is it possible that for some themes, functions.php is not loaded on AJAX calls? I read here that it should be loaded, but it's the only reason I can think of why it works on one site and not the other. I'd attribute this to cache if the item was not updated (rand(1,99 in the example for reference), but the strange thing is that it is actually updated properly just without the filter.

Any pointers would be greatly appreciated!

0

It turns out that some themes disable functions.php for the backend, in order to prevent a complete lockout. The way they do this, is by simply doing an is_admin() check. However, since all AJAX is ran through admin-ajax.php, this returns true, and the theme functions are not loaded. In this particular case (Genesis Framework (theme) with Dynamik website builder (child theme)) there was a setting to enable the theme functions in the backend too, though I personally think it would be much better if the theme just checked for !DOING_AJAX in addition to is_admin()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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