Wordpress ajax请求和定义的常量

时间:2022-11-05 14:53:57

I cannot access my custom defined constants (in functions.php) when I'm doing ajax request with:

当我在执行ajax请求时,我无法访问我的自定义常量(在functions.php中):

add_action( 'wp_ajax_form_request', 'form_request' );
add_action( 'wp_ajax_nopriv_form_request', 'form_request' );

Accessible only standart WP constants, like TEMPLATEPATH.

仅可访问标准WP常量,如TEMPLATEPATH。

Is possible access my own, defined in functions.php?

可以访问我自己的,在functions.php中定义?

1 个解决方案

#1


I just tested something like this and she works just fine:

我刚刚测试了这样的东西,她工作得很好:

In functions.php:

define("MY_CONSTANT", "I am a man of constant sorrows.");

定义(“MY_CONSTANT”,“我是一个不断悲伤的人。”);

Wherever else:

add_action( 'wp_ajax_form_request', 'form_request' );
add_action( 'wp_ajax_nopriv_form_request', 'form_request' );
function form_request()
{
    // check your nonce
    if($_POST['whatever'] == 'get_my_constant_or_whatever')
    {
        header("Content-Type: application/json");
        echo json_encode(MY_CONSTANT);
        exit;
    }
    else
    {
        // do something else or whatever
    }
}

#1


I just tested something like this and she works just fine:

我刚刚测试了这样的东西,她工作得很好:

In functions.php:

define("MY_CONSTANT", "I am a man of constant sorrows.");

定义(“MY_CONSTANT”,“我是一个不断悲伤的人。”);

Wherever else:

add_action( 'wp_ajax_form_request', 'form_request' );
add_action( 'wp_ajax_nopriv_form_request', 'form_request' );
function form_request()
{
    // check your nonce
    if($_POST['whatever'] == 'get_my_constant_or_whatever')
    {
        header("Content-Type: application/json");
        echo json_encode(MY_CONSTANT);
        exit;
    }
    else
    {
        // do something else or whatever
    }
}