I create a template page in WordPress and use add_action to define action that use in Ajax.

/*template name: get_pass

function mda_get_license(){
    echo 54;


and use jQuery code is below:

(function( $ ) {

        function showPass(str) {

            if (str.length != 0) {

                $.post("http://example.com/wp-admin/admin-ajax.php",{action:'my_action1'},function (response) {






when i put add_action in function.php of theme the ajax work but when put the add_action in my template file ajax return 0. i use

global $wp_filter;

to see registered action and saw that two actions registered. now why do i put add_action in my template file the Ajax return 0 while registered action?


The AJAX request is a separate request from the one that renders your page. Your AJAX handler is getting registered on the request that serves the page, but not the AJAX request, which is the one that matters.

Move your add_action and function to your theme's functions.php file, which loads on all requests.

  • does not exist any way that i define add_action in my template?
    – MDA
    Jul 23 '17 at 15:27
  • your template doesn't load on an AJAX request, so your hooked action doesn't exist.
    – Milo
    Jul 24 '17 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.