现在对于我的插件,我正在使用in_admin()
确定用户是在站点前端还是在管理区域。然而,当插件使用admin-ajax.php
处理ajax请求。
我需要一种只在处理时注册挂钩和插件的方法admin-ajax.php
文件或位于网站前端。这样做的最佳方式是什么?
现在对于我的插件,我正在使用in_admin()
确定用户是在站点前端还是在管理区域。然而,当插件使用admin-ajax.php
处理ajax请求。
我需要一种只在处理时注册挂钩和插件的方法admin-ajax.php
文件或位于网站前端。这样做的最佳方式是什么?
检查常数DOING_AJAX
. 它的定义是wp-admin/admin-ajax.php
. 一些非常奇怪的插件,比如Jetpackdefining that constant in unexpected places, 因此,您可以包括is_admin()
也
示例:
if ( is_admin() && defined( \'DOING_AJAX\' ) && DOING_AJAX )
{
// do something
}
我有asked for a simpler way to check this 很久以前,这最终在4.7.0中实现。因此,对于WP 4.7及更高版本,您可以使用:
if ( wp_doing_ajax() )
{
// do something
}
好消息,函数现在已经存在。
File: /wp-includes/load.php
1037: /**
1038: * Determines whether the current request is a WordPress Ajax request.
1039: *
1040: * @since 4.7.0
1041: *
1042: * @return bool True if it\'s a WordPress Ajax request, false otherwise.
1043: */
1044: function wp_doing_ajax() {
1045: /**
1046: * Filters whether the current request is a WordPress Ajax request.
1047: *
1048: * @since 4.7.0
1049: *
1050: * @param bool $wp_doing_ajax Whether the current request is a WordPress Ajax request.
1051: */
1052: return apply_filters( \'wp_doing_ajax\', defined( \'DOING_AJAX\' ) && DOING_AJAX );
1053: }
简单回顾一下admin-ajax.php
定义如下内容。File: /wp-admin/admin-ajax.php
11: /**
12: * Executing Ajax process.
13: *
14: * @since 2.1.0
15: */
16: define( \'DOING_AJAX\', true );
17: if ( ! defined( \'WP_ADMIN\' ) ) {
18: define( \'WP_ADMIN\', true );
19: }
Fuxias解决方案返回false
也适用于从管理面板发出的ajax请求。但这些请求应该会返回true
, 因为您请求的数据是为管理员视图提供的。要解决此问题,可以使用以下功能:
function saveIsAdmin() {
//Ajax request are always identified as administrative interface page
//so let\'s check if we are calling the data for the frontend or backend
if (wp_doing_ajax()) {
$adminUrl = get_admin_url();
//If the referer is an admin url we are requesting the data for the backend
return (substr($_SERVER[\'HTTP_REFERER\'], 0, strlen($adminUrl)) === $adminUrl);
}
//No ajax request just use the normal function
return is_admin();
}
DOING_AJAX
如果你在,经常检查admin-ajax.php
if ( is_admin() && defined( \'DOING_AJAX\' ) && DOING_AJAX )
{
// do something
}
我正在尝试用jQuery编写一个图像库插件。我使用的是jQuerys$。post AJAX方法,用于从相关post页面发送和接收信息。基本上,每次点击“下一步”按钮时,我都会循环浏览附件并添加一个新图像,直到我使用了所有图像(此时我需要返回一些东西来停止AJAX,但还不知道如何…)。我读到了一些关于如何做到这一点的非常矛盾的信息。我非常想知道如何从另一个PHP文件访问WP数据和函数。有什么想法吗?我对这件事感到厌倦、压力大,而且通常都是疯了:)