主题's functions.php中的AJAX操作


AJAX action in theme's functions.php

我已经弄清楚wp_ajax_my_action只工作,如果它被放置在一个插件

有人知道它是否可以在我的主题的函数。php中运行吗?

可以:

在你的页面模板中:

var AjaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
     $.ajax({
          type: "POST",
          url: AjaxUrl,
          data: {
                  action: 'your_action'
          },

在你的functions.php中:

  function your_action() {
    //write your code here
  } 
  add_action('wp_ajax_your_action', 'your_action');
  add_action('wp_ajax_nopriv_your_action', 'your_action');

通过Html表单传递动作

<form name="myform">
   <input type="hidden" name="action" value="custom_action">
   <input type="text"  name="get_first_name" >
   <input type="submit value="submit">
</form>

你的jQuery看起来像这样

    <script>
    jQuery(document).ready(function () 
    {
        var $this = jQuery(this); // Cache this
        jQuery.ajax({
            url: '<?php echo admin_url("admin-ajax.php") ?>', // Let WordPress figure this url out...
            type: 'post',
            dataType: 'JSON', // Set this so we don't need to decode the response...
            data: $this.serialize(), // One-liner form data prep...
            beforeSend: function () {
            // You could do an animation here...
            },
          success: function (data) 
            {
               if (data.status === 'success') {
                        alert("Success");
                        // Here, you could trigger a success message
                } else {
                        // fail 
                }
            }
        });
    });
  </script>

将此代码放入函数文件

function custom_action_function()
{
        $first_name = $_POST['get_first_name'];
        /* fetch your form variable here */
        if('your condition') // your condition if success
        {    
                echo json_encode(array('status' => 'success', 'message' => 'Message Sent.'));
                exit;
        }
        else
        {
             echo json_encode(array('status' => 'error', 'message' => 'Message not sent'));
               exit; 
        }    

}
add_action('wp_ajax_custom_action', 'custom_action_function'); // Call when user logged in
add_action('wp_ajax_nopriv_custom_action', 'custom_action_function'); // Call when user in not logged in