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

Asked

Viewed 772 times

2

When I make an AJAX request in Wordpress I do it in two ways, but I would like to know which is the best.

The two I know are:

1º) You put your function in functions, for example:

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 in it the Wordpress functions by wp-blog-header and make the return.

So, is there any other way? Which one would be better? 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.

1 answer

2

Using the second form you will load Wordpress twice: once on load page and the second when including the wp-blog-header.php or wp-load.php. Has a post on Crappy Code dedicated to it: wp-load.php - I Will Find You!

The correct is the first way, calling AJAX through the actions wp_ajax_* (being the nopriv for users who are not logged in) and passing the URL of wp-ajax.php (and nonce of security) through the 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' ) 
    ) 
);

Example of full plugin: How to Use AJAX in a Wordpress Shortcode?

  • When I used functions, it occurred on some servers gives error 404(not found) or 505.. But out of nowhere returned to normal, already went through this?

  • No, I’ve never seen... how do you mount the URL’s admin-ajax.php? . . . And, just remembering, if the functionality you implement has to survive if you change from Theme, then one should use a plugin instead of putting in functions.php.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.