Wordpress Ajax Frontend

The ajaxurl is not exposed to front end by default, so lets add it to the header first.

function set_ajaxurl(){
    echo '<script type="text/javascript"> var _ajaxurl = "'.admin_url("admin-ajax.php").'";</script>';
}
add_action( 'wp_head', 'set_ajaxurl' );

And then we make a action function for our ajax

function ajax_action(){
    //do something with the $_POST data here
    //like you do with normal WordPress stuffs

    exit(); //this is needed
}

add_action( 'wp_ajax_nopriv_ajax_action', 'ajax_action' );

Take note of the wp_ajax_nopriv_ajax_action the “nopriv” makes it available to non logged in users. If you want to make you script work for logged in users as well, you need to duplicate your hook with the normal wp_ajax_ajax_action like so.

add_action( 'wp_ajax_ajax_action', 'ajax_action' );

Amiel Simbahon

Amiel Simbahon
Software Maker

Option Page for your Plugin or Theme

How to add option page to your plugin or theme. Continue reading

Human Readable Filesize

Published on February 21, 2017

PHP Date Quirks

Published on February 20, 2017