我知道这是一个古老的问题,但想添加我自己的答案,我认为这可能会帮助某些尝试实现同一目标的用户。
是的,使用本机WP Ajax API总是更好(也更容易),但是由于它会加载整个WP实例,因此它变得非常慢。
我的解决方案:非常简单,应该可以检索root
wordpress安装。在执行自定义AJAX调用的任何脚本中,只需确保首先注册脚本即可wp_register_script()
(不要将其加入队列)。然后使用wp_localize_script()
并解析ABSPATH
(这是在内部定义的常量,wp-load.php
将保留根路径)。现在,您可以在脚本中检索此内容,并将其与AJAX调用一起解析。最后,当然要确保使用真正使脚本入队wp_enqueue_script()
。
例:
下面的PHP代码段将使您的script.js
文件排队,并允许您root
通过调用检索目录pluginslug_scriptname_i18n.wp_root
。基本上,wp_localize_script()
用来进行翻译,但这也很方便将数据解析到您在服务器端检索到的脚本中。
$handle = 'pluginslug-scriptname'; // Set script handle
$name = str_replace( '-', '_', $handle ) . '_i18n'; // Will convert handle to pluginslug_scriptname_i18n
wp_register_script( $handle, plugin_dir_url( __FILE__ ) . 'script.js', array(), '1.0.0', false );
wp_localize_script(
$handle,
$name,
array(
'ajax_url' => plugin_dir_url( __FILE__ ) . 'ajax-handler.php', // @THIS WILL HOLD YOUR AJAX URL :) To retrieve this inside your script.js simply call: pluginslug_scriptname_i18n.ajax_url
'wp_root' => ABSPATH // @THIS WILL HOLD THE ROOT PATH :) To retrieve this inside your script.js simply call: pluginslug_scriptname_i18n.wp_root
)
);
wp_enqueue_script( $handle );
您script.js
可能看起来像这样:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 ){
if (this.status == 200) {
// Success:
}
// Complete:
}
};
xhttp.onerror = function () {
console.log(this);
console.log("** An error occurred during the transaction");
};
xhttp.open("POST", pluginslug_scriptname_i18n.ajax_url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
var params = JSON.stringify({
first_name: 'Johny',
wp_root: pluginslug_scriptname_i18n.wp_root
});
xhttp.send(params);
现在,您ajax-handler.php
可以在其中检索wp_content_dir
和加载您的内容,wp-load.php
如下所示:
// Set proper content type
header('Content-Type: text/html');
// Disable caching
header('Cache-Control: no-cache');
header('Pragma: no-cache');
// Get's the payload
$request_body = json_decode( file_get_contents('php://input'), true );
// Set this to true to just load the basics!
// Only set this to true if you know what you are doing
// Lookup SHORTINIT inside wp-settings.php for more details
define( 'SHORTINIT', false );
// Include wp-load.php
require_once( $request_body['wp_root'] . 'wp-load.php' );
die();
请记住,wp_root
可以更改客户端。
附带说明:
你们中有些人可能不知道的另一个技巧是,在包括之前,wp-load.php
您可以定义一个称为SHORTINIT
(boolean)的常量。这将告诉WordPress仅加载基础知识(这意味着您将失去很多WP核心功能),但由于它不包含常规WP实例的所有必需文件,因此将加快加载时间。该SHORTINIT
定义中wp-settings.php
(刚打开文件,查找SHORTINIT
,您将有更好的理解什么是引擎盖下发生的。这个漂亮的把戏,在我的测试中,我没有更多的(最多加快加载时间75% ),但这要取决于WP版本。另外请记住,wp-load.php
随着WP版本的新版本的发布,更改经常发生,因此如果您使用SHORTINIT
确保您的脚本即使在未来的WordPress版本以及较低版本的WordPress中也将始终可用。简而言之,如果您执行依赖于很多WordPress Codex的复杂操作,请确保不要将其设置SHORTINIT
为true。