問題描述

現在我的插件,我正在使用 in_admin()來確定用户是在該站點的前端還是在管理區域。但是,當插件使用 admin-ajax.php 處理 ajax 請求時,會出現此問題。

只有在處理 admin-ajax.php 文件或站點的前端時,才需要註冊鈎子和插件。做這個的最好的方法是什麼?

最佳解決方案

檢查常數 DOING_AJAX 。它的定義是 wp-admin/admin-ajax.php 中的第一個工作代碼。一些非常奇怪的插件,如 Jetpack,是 defining 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: }

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。