首页 > 解决方案 > 做 ajax 的 WordPress 总是返回 0,但在某些情况下应该返回 1

问题描述

我在 WordPress 中为我的插件创建了一个 AJAX 函数。在插件构造中,我定义了 AJAX 回调:

public function __construct() {
    return $this->register();
}

/**
 * Register all new files in WooCommerce hooks
 */
public function register() {
    if ( is_user_logged_in() ) {
        add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
    } else {
        add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );
    }
}

这是触发 AJAX 调用的 jQuery 函数:

jQuery(document).ready(function () {
    jQuery(document).on('click', '.filter-menu li', function () {
        var filter_value = jQuery(this).find('.menu-data-inner');

            var data = {
                'action': 'filter',
                'filter': filter_value.attr('data-value'),
                'filter_status': 1
            };      

            var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";

            jQuery.post(ajaxurl, data, function () {
                jQuery('#content-area').load(location.href + ' #content-area>*', '');
            });
        }
    });
});

在我的请求结束时,我通过 AJAX 刷新了 WordPress 主要内容,并期望我在functions.phpget 中的函数因为DOING_AJAX.


这是 AJAX 请求调用的函数:

/**
 * Filter
 */
public function filter() {
    require 'functions/filter.php';
    wp_die();
}

这是require的内容:

<?php error_log( $_POST['filter'] ); ?>

所以我的问题是现在我已将此功能添加到我的functions.php

add_action( 'init', 'do_something' );
function do_something() {
    error_log('INIT');
}

但是我很快就看到这会导致问题,因为在 AJAX 请求上也调用了 init get,但我不希望这样。它应该只在通过按或输入站点 URLINIT加载页面并按 Enter 时打印。F5所以我添加了一张支票:

add_action( 'init', 'do_something' );
function do_something() {
    if ( ! wp_doing_ajax() ) {
        error_log('INIT')
    }
}

但是在再次调用 AJAX 之后,调试日志也打印了 INIT 但它不应该。因此,我尝试以这种方式修改在 AJAX 期间调用的函数:

<?php 
    error_log( $_POST['filter'] ); 

    define( 'DOING_AJAX', true ); ?>

但这也没有成功。error_log还在。

那么问题是什么?我在这里做错了什么?我的意思是我已经像在 DOCS 中那样做了,但似乎 DOING_AJAX 对我不起作用。

标签: phpjqueryajaxwordpress

解决方案


你需要

add_action( 'wp_ajax_filter', array( $this, 'filter' ) );

每次您发送 ajax 请求,但这

add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );

当您需要该用户未登录时,这将更改为:

public function register() {
    if ( is_user_logged_in() ) {
        add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
    } else {
        add_action( 'wp_ajax_filter', array( $this, 'filter' ) );
        add_action( 'wp_ajax_nopriv_filter', array( $this, 'filter' ) );
    }
}

这就是我猜任何请求都会得到 0 的原因


推荐阅读