如何从任何位置包括wp-load.php?


12

我有一个插件,可通过插件内的jQuery.ajax()脚本调用独立的php脚本(myAjax.php)。

我需要将以下代码放入myAjax.php文件中:

require_once('../../../wp-load.php');

if (!is_user_logged_in()){
    die("You Must Be Logged In to Access This");
}
if( ! current_user_can('edit_files')) {
    die("Sorry you are not authorized to access this file");
}

但是,如果实际的相对路径与我的示例不同,我想使用一种更加防弹的方法来指定wp-load.php的路径。



除了Milo所说的以外,这里还有2条关于该主题的精彩文章。garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress最新版本ottopress.com/2010/dont-include-wp-load-please最新版本)也是为了学习,第一次幻灯片放映andrewnacin.com/2011/04/16/wordcamp-seattle最新版本
Wyck,

Answers:


6

您可以使用__DIR__常量。由于该文件位于插件或主题文件夹中,因此始终位于该wp-content文件夹内。.您可以简单地获取文件的路径并从该文件开始修剪所有wp-content内容:

$path = preg_replace('/wp-content.*$/','',__DIR__);

如果您需要确定wp不在某个wp-content文件夹中(谁知道?事情会发生)-使用否定的超前查询:

$path = preg_replace('/wp-content(?!.*wp-content).*/','',__DIR__);

(因为更容易确保正在开发的自己的插件不在其他wp-content文件夹中)

Aaand ..您wp-load在那里:

include($path.'wp-load.php');

但!

如前所述,对于AJAX,您可以使用WP的本机ajax技术

当然,在某些情况下,WP的本机AJAX技术还不够。


3
wp-content可能不存在,或者与WP不在一个完全不同的目录中。
fuxia

这可能是最好的方法。如果您有奇怪的wp-content位置(不太可能),只需调整您的正则表达式即可。
pguardiario

0

我知道这是一个古老的问题,但想添加我自己的答案,我认为这可能会帮助某些尝试实现同一目标的用户。

是的,使用本机WP Ajax API总是更好(也更容易),但是由于它会加载整个WP实例,因此它变得非常慢。

我的解决方案:非常简单,应该可以检索rootwordpress安装。在执行自定义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的复杂操作,请确保不要将其设置SHORTINITtrue


-1

您可以使用以下代码使用wp-load.php从任何位置包含wp-load

require_once( trailingslashit( ABSPATH ) .'wp-load.php' );

2
但是,如果已经设置了ABSPATH并定义了结尾斜杠,那么您可能已经包含了wp-load。
Rup
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.