admin管理员组

文章数量:1122832

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/api/news.php, the JSON prints correctly, but if I go to www.example/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?

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?

Share Improve this question edited Mar 29, 2016 at 18:50 Hutch Moore 277 bronze badges asked Mar 29, 2016 at 18:33 BryanBryan 1014 bronze badges 2
  • Do you have any errors in your browser console? This might be a same origin issue – czerspalace Commented Mar 29, 2016 at 18:52
  • @czerspalace Nope, no errors – Bryan Commented Mar 29, 2016 at 18:53
Add a comment  | 

2 Answers 2

Reset to default 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);
  });

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

本文标签: wp queryHow To Call WPQuery From A Subdomain