Created
November 18, 2016 11:07
-
-
Save forsvunnet/b31f50ddc034b40cb1de361d895f0bbf to your computer and use it in GitHub Desktop.
WordPress ajax plugin example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Replace name_of_action with the name of the ajax action; | |
Replace name-of-plugin and name_of_plugin with the name of the plugin | |
File: name-of-plugin.php | |
<?php | |
class name_of_plugin { | |
/** | |
* Setup | |
*/ | |
static function setup { | |
self::_include( 'name-of-plugin-ajax' ); | |
name_of_plugin_ajax::setup(); | |
} | |
/** | |
* Include | |
* Helper method to load class files | |
* @param string $class | |
*/ | |
static function _include( $class ) { | |
require_once __DIR__ ."/includes/class-{$class}.php"; | |
} | |
/** | |
* Get plugin URL | |
* @param string $path | |
* @return string | |
*/ | |
static function get_plugin_url( $path = '' ) { | |
return plugin_dir_url( __FILE__ ) . $path; | |
} | |
} | |
name_of_plugin::setup(); | |
?> | |
File: includes/class-name-of-plugin-ajax.php | |
<?php | |
class name_of_plugin_ajax { | |
/** | |
* Setup | |
*/ | |
static function setup() { | |
$action = 'name_of_action'; | |
add_action( 'wp_enqueue_scripts', __CLASS__ .'::enqueue_scripts' ); | |
add_action( 'wp_ajax_name_of_action', __CLASS__ .'::name_of_action' ); | |
add_action( 'wp_ajax_nopriv_name_of_action', __CLASS__ .'::name_of_action' ); | |
} | |
/** | |
* Enqueue scripts | |
*/ | |
static function enqueue_scripts() { | |
// Register the script | |
wp_register_script( 'name_of_plugin', name_of_plugin::get_plugin_url() .'assets/name-of-plugin.js' ); | |
// Localize the script with new data | |
wp_localize_script( 'name_of_plugin', 'name_of_plugin', [ | |
'ajax_url' => admin_url( 'admin-ajax.php' ), | |
] ); | |
// Enqueued script with localized data. | |
wp_enqueue_script( 'name_of_plugin' ); | |
} | |
static function name_of_action() { | |
// Use $_POST data to get data from the ajax call | |
$json = json_encode( /* Code here */ ); | |
header('Content-Type: application/json'); | |
die( $json ); | |
} | |
} | |
?> | |
File: assets/name-of-plugin.js | |
jQuery( function() { | |
$.post( name_of_plugin.ajax_url, { | |
action: name_of_action, | |
// .. other post data here | |
}, function( data ) { | |
// .. do stuff with data here | |
} ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment