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
2 Answers
Reset to default 0Why 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
版权声明:本文标题:wp query - How To Call WP_Query From A Subdomain? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736290844a1928596.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论