Skip to content

Instantly share code, notes, and snippets.

@wpdevsol
Forked from abelcallejo/README.md
Created August 12, 2022 09:58
Show Gist options
  • Save wpdevsol/8fe4130d167d9c6eb37d4d9eb1afa544 to your computer and use it in GitHub Desktop.
Save wpdevsol/8fe4130d167d9c6eb37d4d9eb1afa544 to your computer and use it in GitHub Desktop.
Wordpress AJAX Cheatsheet

Wordpress AJAX Cheatsheet

Table of contents

  1. Adding ajaxurl for the public side (optional)
  2. Preparing callable functions
  3. jQuery implementation

1. Adding ajaxurl for the public side

This step is optional. You may need it only for ajax implementations on the public front-end.

add_action('wp_head', 'add_public_ajaxurl');

function add_public_ajaxurl() {
    ?><script type="text/javascript">var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";</script><?php
}

2. Preparing callable functions

Hook for the admin side

add_action("wp_ajax_{$action}", "callable_function"); // wp_ajax_register

Hook for the public side

This step is optional. You may need it only for ajax implementations on the public front-end.

add_action("wp_ajax_nopriv_{$action}", "callable_function"); // wp_ajax_nopriv_register

3. jQuery implementation

var data = {
   action: 'register',
   key_1: 'value_1',
   key_2: 'value_2'
};

Asynchronous POST

jQuery.post( ajaxurl, data , function( json ) {
   console.log( json );
}, "json");

Asynchronous GET

jQuery.get( ajaxurl, data , function( json ) {
   console.log( json );
}, "json");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment