• Resolved tim71

    (@tim71)


    I need a stand alone backend php page (outside of wordpress) to return json results and also be able to utilize wpdb class for database access.

    From what I read this should be fairly straight forward but 5 hours later I am still receiving some unexpected results. I have simplified the code down to the nuts and bolts but I’m not sure what is going on here.

    The following code returns the expected json result: {"id":"test"}

    <?php
     		define('WP_USE_THEMES', false);
    		$jsonpost = array();
    		$jsonpost["id"] = "test";
    		$encoded=json_encode($jsonpost);
    		die($encoded);
    ?>

    However, when I attempt to include wp-load.php to bootstrap to the wordpress functions. I receive the following with the json result appended to the end:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="https://www.w3.org/1999/xhtml">
    <head></head>
    <body></body>
    </html>
    {"id":"test"}

    Here is the exact code that produced this result:

    <?php
     		define('WP_USE_THEMES', false);
    		$jsonpost = array();
    		$jsonpost["id"] = "test";
    		$encoded=json_encode($jsonpost);
                    //alter path to your specific location
    		require_once("../../../wp-load.php");
    		die($encoded);
    ?>

    The only difference was including the wp-load file. The link below is where I started however I have attempted other simple examples using cut and paste and it always returns the html page before json result when wp-load is included.

    https://www.mlynn.org/2010/12/wordpress-extjs-displaying-posts-in-an-extjs-grid/

    Any ideas on how to get this to work with wp-load file included?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator Samuel Wood (Otto)

    (@otto42)

    www.ads-software.com Admin

    Argh…

    Don’t include wp-load.

    Including wp-load is doing-it-wrong(tm), always.

    In your case, you could either do this using the AJAX approach (See https://codex.www.ads-software.com/AJAX_in_Plugins) or using a more direct approach on the init action. Which way is correct depends on what exactly you’re doing (that isn’t a simple example).

    For example, this code in a plugin would do more what you’re expecting:

    add_action('init','produce_my_json');
    function produce_my_json() {
      if (!empty($_GET['example'])) {
        $jsonpost = array();
        $jsonpost["id"] = "test";
        $encoded=json_encode($jsonpost);
        header( 'Content-Type: application/json' );
        echo $encoded;
        exit;
      }
    }

    Then a call to https://example.com/?example=1 will give you back your json instead of WordPress.

    There’s other ways, depending on the specific goal. You could use the add_feed mechanism to create a json output of posts and such if desired. Or you use the ajax handler to produce general output. Or whatever. The exact method will vary depending on the desired output, but it is *always* wrong to do an include of wp-load.php in a separate file. There is *always* a better way.

    Thread Starter tim71

    (@tim71)

    Otto,

    I believe what you say and typically do exactly what you advocate however in this case it is being posted to by SWFUpload and I took my cue from WordPress itself as well as NGG_Gallery Code.

    I did get it working using the rightfully dreaded wp-load technique. Does anyone know why wordpress and NGG_Gallery both use wp-load in a standalone page to post to?

    WordPress (async-upload.php):

    <?php
    /**
     * Accepts file uploads from swfupload or other asynchronous upload methods.
     *
     * @package WordPress
     * @subpackage Administration
     */
    
    define('WP_ADMIN', true);
    
    if ( defined('ABSPATH') )
    	require_once(ABSPATH . 'wp-load.php');
    else
    	require_once('../wp-load.php');
    
    ...
    Moderator Samuel Wood (Otto)

    (@otto42)

    www.ads-software.com Admin

    WordPress knows where its files are in relation to itself. In other words, wp-load.php is always going to be one directory up from async-upload.php. The wp-admin and wp-includes directories can’t be moved around and have WP still work.

    A plugin, however, is not always going to be in /wp-content/plugins. wp-content can be moved. So can the plugins. Ditto for themes. So you have no way to know that ../../../wp-load.php will be correct. In many cases, it won’t be. I have several sites where wp-content is elsewhere entirely, and your code won’t work. For example, in one case, it would have to be ../../../wp/wp-load.php. There is no good way for a plugin to figure that out.

    This is not a problem for a single one-off usage, of course. But if you’re making things for other people to use, then you should be more generic than that.

    NGG_Gallery is doing-it-wrong.

    Thread Starter tim71

    (@tim71)

    Thanks for the advice Otto. Much appreciated.

    Thread Starter tim71

    (@tim71)

    Ok. I basically did as you suggested and it works great with one exception…

    I need current_user within the function and I cannot get_currentuserinfo() in function produce_my_json. My code is as follows…

    // Flash often fails to send cookies with the POST or upload, so we need to pass it in GET or POST instead
    		if ( is_ssl() && empty($_COOKIE[SECURE_AUTH_COOKIE]) && !empty($_REQUEST['auth_cookie']) )
    			$_COOKIE[SECURE_AUTH_COOKIE] = $_REQUEST['auth_cookie'];
    		elseif ( empty($_COOKIE[AUTH_COOKIE]) && !empty($_REQUEST['auth_cookie']) )
    			$_COOKIE[AUTH_COOKIE] = $_REQUEST['auth_cookie'];
    		if ( empty($_COOKIE[LOGGED_IN_COOKIE]) && !empty($_REQUEST['logged_in_cookie']) )
    			$_COOKIE[LOGGED_IN_COOKIE] = $_REQUEST['logged_in_cookie'];
    
    			unset($current_user);
    			 get_currentuserinfo();

    This works on the standalone page however it does not work within the ajax page as described above ($current_user is empty).

    I did manage to manually set the current user with the following code…

    $user = wp_validate_auth_cookie();
    wp_set_current_user($user);

    So I guess the question is why no $current_user in the ajax function? And is it ok to set it manually with the above code?

    -Tim

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Json result from 'outside wordpress'’ is closed to new replies.