Hook AJAX in Wordpress

前端 未结 2 1637
情话喂你
情话喂你 2020-12-04 01:22

I have been delving into the world of Javascript and AJAX. I am super close, but for some reason I do not think I am hooking into wordpress ajax functions right. I have pour

2条回答
  •  执念已碎
    2020-12-04 01:54

    First of all you need to add hooks in proper way

    // For the users that are not logged in
    add_action( 'wp_ajax_nopriv_addItemAJAX', 'addItemAJAX_callback' );  
    
    // For the users that are  logged in:  
    add_action( 'wp_ajax_addItemAJAX', 'addItemAJAX_callback' );
    
    // ajax handler
    function addItemAJAX_callback()
    {
        // code goes here
        // since $debugArray is an array, so 
        die(json_encode($debugArray)); // last line
    }
    

    One hook will work when user is logged in and another will work when user is not logged in (for any user). If you are making ajax request for logged in users then, wp_ajax_nopriv_ hook is required.

    Keep your js/ajax code in a separate file in yourthemefolder/js/myAjaxScript.js and also keep following code in your functions.php file

    add_action('wp_enqueue_scripts', 'my_load_scripts');
    function my_load_scripts()
    {
        // for pluggin, you may use "plugin_dir_url( __FILE__ )"
        wp_enqueue_script( 'my_ajax-script', get_stylesheet_directory_uri() . '/js/myAjaxScript.js', array('jquery') );
    
        // Following code will let you use "ajaxObj.ajax_url" to get the
        //  ajax url (admin-ajax.php) in your my_ajax_scriptjs file
        wp_localize_script(
            'my_ajax-script', 'ajaxObj', array( 'ajax_url' => admin_url( 'admin-ajax.php' )                
        ));
    }
    

    In your my_ajax_script.js file, you may code like this

    var data = {
         action: 'addItemAJAX_callback',
         // ...
    };
    $.getJson(ajaxObj.ajax_url, data, function(response) {
         // response is an object
         // ...
    });
    

    Alos remember, when using ajax from admin panel, you don't need to use wp_localize_script, since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php.

提交回复
热议问题