What is the best way to make an AJAX request in WordPress?

2

When I make an AJAX request in WordPress I do it in two ways, but I'd like to know which one is best.

The two that I know of are:

1º) You put your function in functions, eg:

add_action('wp_ajax_nopriv_my-function','my_function');
add_action('wp_ajax_busca-my-function','my_function');
function my_function(){
  //code
}

2nd) You create a file, call it the Wordpress functions through wp-blog-header and make the return.

So, is there any other way? Which one would be the best? I'm developing a news portal, and the idea is to have a timeline like Stack Overflow, where every new news the customer is notified to update.

    
asked by anonymous 01.11.2014 / 21:35

1 answer

2

Using the second form you will load WordPress twice: one in the normal load of the page and the second one when adding wp-blog-header.php or wp-load.php . You have a post on Crappy Code dedicated to this: wp-load.php - I Will Find You!

Correct is the 1st form, calling AJAX through actions wp_ajax_* (being nopriv for users that are not logged in) and passing the URL of wp-ajax.php (and nonce security) through wp_localize_script :

wp_enqueue_script( 
    'meu-ajax',       // handler
    get_template_directory_uri() . '/js/meu-ajax.js', // ou plugins_url( '/js/meu-ajax.js', __FILE__ )
    array( 'jquery' ) // dependencia
);
wp_localize_script( 
    'meu-ajax',       // handler
    'wp_ajax',        // objeto disponível em meu-ajax.js
    array( 
         'ajaxurl'   => admin_url( 'admin-ajax.php' ),
         'ajaxnonce' => wp_create_nonce( 'ajax_post_validation' ) 
    ) 
);

Complete plugin example: How to use AJAX in a WordPress Shortcode?

    
01.11.2014 / 22:53