Include Wordpress Core into own Scripts

前端 未结 3 1936
深忆病人
深忆病人 2020-12-08 08:33

I\'m trying to \"Import\" the Wordpress core into an own script to use the functionality such as wp_query etc. I\'ve created an script in a subdirectory (own framework) and

3条回答
  •  眼角桃花
    2020-12-08 09:13

    Short answer, do this:

    define('WP_USE_THEMES', false);
    global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
    require(BASE_PATH . 'wp-load.php');
    

    Long answer, it's a subtle gotcha around importing scripts with PHP.

    If you define a local variable, outside of all functions, then it can be retrieved inside a function using 'global'. If you have a local variable inside a function, it cannot be retrieved later using global, unless it is defined as being global there and then.

    The script 'wp-settings.php' is where the issue lies. It is included via your call to include 'wp-load.php'.

    The variables defined there are not stated as being global; instead this is presumed because the script is always run outside of any functions, and so are automatically global. i.e.

    $wordpress = 'foo';
    
    function wordpressFunction() {
        global $wordpress;
    }
    

    Because you are importing the script within a function, they now become local variables. You are essentially doing:

    function myFramework() {
        $wordpress = 'foo';
    
        function wordpressFunction() {
            global $wordpress;
        }
    }
    

    So the fix is to define them as global yourself before importing the script. Now $wp_query, and the others defined as global, are correctly found.

提交回复
热议问题