Accessing wordpress DB object (wpdb) from an external server

Sorry in advance for the noob-question.

I’ve scoured Google and StackOverflow and have found plenty of ways to access wpdb on a php page when you’re on the same server, but no one seems to have an answer to calling it from an entirely different server.

Read More

I’m trying to create a plugin in Piwik that queries our multi-site WP DB (hosted on a separate server from Piwik) to get the total count of posts. The query is easy when you use the wpdb class (e.g., $wpdb->get_results)… but not so easy if you try to run a straight SQL query since you’d have to tally up a count from 60+ tables, hence my desire to use wpdb to grab all the useful functions.

That being said, using require_once( 'http://www.example.com/wordpress/wp-load.php' ); (h/t to stormmyfrog) to access the wpdb object isn’t very secure if you set allow_url_include=1. Is there another way to get around this?

Related posts

Leave a Reply

1 comment

  1. Using require_once( 'http://www.example.com/wordpress/wp-load.php' ); Won’t work from external locations even if you allow_url_include. Your server still parses the php file and sends the parsed php which would end up being completely blank.

    What you need to do is create an API. You will probably want to create a WordPress plugin that creates a new url that Piwik can query to get the results.

    A super simple api on the WordPress server could look like this:

    /api.php

    <?php
    
    // TODO add authentication, probably token-based
    // TODO move this to a WP plugin
    
    include ('wp-load.php');
    
    // Get count of published posts
    $count = array(
        'count' => wp_count_posts()->publish
    );
    
    echo json_encode($count);
    

    PIWIK SITE

    <?php
    
    $data = json_decode(file_get_contents('http://www.example.com/wordpress/api.php'));
    
    echo $data->count;
    // Result: number of published posts