Skip to content

Instantly share code, notes, and snippets.

@giventofly
Created May 4, 2018 14:44
Show Gist options
  • Save giventofly/1f52377a7162eae5c773cf725170ed3b to your computer and use it in GitHub Desktop.
Save giventofly/1f52377a7162eae5c773cf725170ed3b to your computer and use it in GitHub Desktop.
wordpress add admin menu item post ajax request on button press
//add a menu page with a button to do stuff
add_action('admin_menu', 'my_menu_pages');
function my_menu_pages(){
add_menu_page('Actualizar Liga Magus', 'Actualizar Liga', 'manage_options', 'my-menu', 'my_menu_output','',0 );
}
function my_menu_output(){
$html = '<a href="#ajaxthing" class="myajax">Teste</a>';
echo $html;
}
add_action('admin_head', 'my_action_javascript');
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
let value = 1234;
$('.myajax').click(function(){
var data = {
action: 'my_function_name',
whatever: value
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(ajaxurl, data, function(response) {
value = value + response;
alert('Got this from the server: ' + response);
});
});
});
</script>
<?php
}
add_action('wp_ajax_my_function_name', 'my_exec_me');
function my_exec_me() {
//global $wpdb; // this is how you get access to the database
$whatever = $_POST['whatever'];
$whatever += 10;
echo $whatever;
exit(); // this is required to return a proper result & exit is faster than die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment