Fatal error: Call to undefined function wp_create_nonce()

I’m trying to add a nonce to my plugin’s Ajax. I’m not sure why I’m getting this error:

Fatal error: Call to undefined function wp_create_nonce()

Read More

In my php file :

wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl'=> admin_url('admin-ajax.php'), 'my_nonce' => wp_create_nonce('myajax-nonce')));

In js file:

jQuery.post(the_ajax_script.ajaxurl, {my_nonce : the_ajax_script.my_nonce}, jQuery("#theForm").serialize() + "&maxLat="+ map_bounds[0] + "&maxLong="+ map_bounds[1] + "&minLat="+ map_bounds[2] + "&minLong="+ map_bounds[3],
    function(response_from_the_action_function){
       jQuery("#response_area").html(response_from_the_action_function);
    });

Any suggestions on how to solve this?

Thank you.

Related posts

Leave a Reply

1 comment

  1. More context would be helpful. Is that all the code found in your plugin or functions file directly? Or are you hooking in to something via add_action.

    Anyway, what’s probably wrong is that you’re calling wp_localize_script and wp_enqueue_script outside of an action. wp_create_nonce, or, rather, the file in which it resides, has yet to be loaded.

    The solution is to call wp_localize_script from inside a function hooked into wp_enqueue_scripts

    <?php
    add_action( 'wp_enqueue_scripts', 'wpse30583_enqueue' );
    function wpse30583_enqueue()
    {
        // your enqueue will probably look different.
        wp_enqueue_script( 'wpse30583_script' );
    
        // Localize the script
        $data = array( 
            'ajax_url' => admin_url( 'admin-ajax.php' ),
            'nonce'    => wp_create_nonce( 'wpse30583_nonce' )
        );
        wp_localize_script( 'wpse30583_script', 'wpse3058_object', $data );
    }