0

I have a PHP script running in WordPress, that uses a WP_Query to get the posts from one of my subdomains and return it as a JSON string. The script only receives the post data if I call it using the correct subdomain.

For example, if I go to news.example.com/api/news.php, the JSON prints correctly, but if I go to www.example.com/api/news.php it only prints an empty array.

How can I call a single script that will get data from a subdomain, even if I call it using the main domain? Or even better, if I call it from any subdomain?

  • Do you have any errors in your browser console? This might be a same origin issue – czerspalace Mar 29 '16 at 18:52
  • @czerspalace Nope, no errors – Bryan Mar 29 '16 at 18:53
0

Why don't you try using the WP API?

You could then pull posts from a URL like this ...

http://subdomain.example.com/wp-json/posts

You can also set custom post types to use the WP API and then access them also in a similar manner, you would need to add the following to your CPT args:

$args = array(
         //...
        'show_in_rest'       => true,
        'rest_base'          => 'books-api',
        'rest_controller_class' => 'WP_REST_Posts_Controller',
       )
    );

Take a look at: http://v2.wp-api.org/extending/custom-content-types/

You can even use WP_Query parameters like this:

http://subdomain.example.com/wp-json/posts?filter[posts_per_page]=2&filter[order]=ASC

You could use jQuery.getJSON() to get the data cross domain:

 $.getJSON('http://subdomain.example.com/wp-json/posts', function (data) {
    console.log(data);
  });
  • Interesting, but how would it solve the problem of accessing the content from a different subdomain? Also, from what I've read, you cannot do authentication with the Rest API, which some of my feeds would require. – Bryan Mar 29 '16 at 19:04
  • I'm obviously not 100% sure what you are trying to achieve, but could you not force the user to authenticate before they see a page with any of the feeds on? This should work cross-domain using jQuery.getJSON() I think, I've added to my answer... – Dammeul Mar 29 '16 at 19:10
0

Alternatively you can include the wordpress functions in any *.php file anywhere on your server. You don`t have to run the script inside the actual WP installation:

define('WP_USE_THEMES', false);
require('/absolute/path/to/your/httpdocs/wp-blog-header.php');
require('/absolute/path/to/your/httpdocs/wp-admin/includes/admin.php');

Just include the headers and for admin-functions the admin.php. Then you can WP-Query() in this (external) file.

Regards Tom

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.