Skip to content

Instantly share code, notes, and snippets.

@sophiawzey
Created October 9, 2019 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sophiawzey/2ca54708a010fe6e60fcaa7091d93984 to your computer and use it in GitHub Desktop.
Save sophiawzey/2ca54708a010fe6e60fcaa7091d93984 to your computer and use it in GitHub Desktop.
[WP AJAX] #ajax
<?php
function exampleAjaxResponse()
{
die(); // or exit; or wp_die();
}
// Note you need both of them to work for logged in & not logged in users.
add_action('wp_ajax_your_action_name', 'exampleAjaxResponse');
add_action('wp_ajax_nopriv_your_action_name', 'exampleAjaxResponse');
function onlyWorksIfUserLoggedIn()
{
die(); // or exit; or wp_die();
}
// Note if it should only work for users logged in, do this. Now, it's secure.
add_action('wp_ajax_your_action_name', 'onlyWorksIfUserLoggedIn');
function catchesAVariable()
{
// be sure to check for empty values and provide a default
$name = !empty($_POST['name']) ? $_POST['name'] : 'My default value';
die(); // or exit; or wp_die();
}
add_action('wp_ajax_your_action_name', 'catchesAVariable');
function returningJson()
{
// be sure to check for empty values and provide a default
$name = !empty($_POST['name']) ? $_POST['name'] : 'My default value';
// note - wp_send_json automatically returns json & calls die();
wp_send_json(['name' => $name]);
}
add_action('wp_ajax_your_action_name', 'returningJson');
function returningHtml()
{
$page = !empty($_POST['page']) ? $_POST['page'] : 0;
$html = wp_query_or_something();
// just echo out the html
echo $html;
die();
}
add_action('wp_ajax_your_action_name', 'returningHtml');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment