背景
Wordpress是一个广泛使用的CMS框架,无数的自媒体,新闻站点都使用它作为内容发布站。Meteor可以轻松开发移动端的Hybrid应用并且发布到Android,iOS等平台。本文讲述了在Meteor中如何通过API获取Wordpress站点数据。
部署Wordpress开发环境
下载Kitematic,也就是Docker Toolbox,Docker的GUI版本安装Docker。具体教程请参见使用DaoCloud安装Docker和镜像。
然后安装docker-wordpress-nginx这个image。快速搭建一个能够运行的Wordpress系统。首先打开Kitematic,然后连接到Docker CLI。
根据国内具体国情,需要安装 DaoCloud的Docker Hub 加速器。
curl -sSL https://get.daocloud.io/daomonit/install.sh | sh -s 7a6d83cbe808b4这里用你自己的825fbcc77d451d82f
安装完成后,就可以使用dao
代替docker
实现跨墙获取镜像。
dao pull eugeneware/docker-wordpress-nginx
** Pull eugeneware/docker-wordpress-nginx success. **
You can find it with 'docker images eugeneware/docker-wordpress-nginx'
第一次运行时,指定端口和名称,这里docker-wordpress-nginx
表示的是这一特定配置运行的container,唯一。
docker run -p 80:80 --name docker-wordpress-nginx -d eugeneware/docker-wordpress-nginx
然后在我们的Kitematic中可以看到Container Logs和Web Preview,我们通过http://192.168.99.100/
访问Wordpress,因为这里Boot2docker VM绑定了192.168.99.100这个IP,所以访问不是通过localhost了。
Posts内容获取
我在想在wordpress中如何写一个api接口,请求这个网址,可以获取最新文章列表,一般通常的做法是新建一个php文件,接收几个参数,查询数据库,用json格式返回数据就行了,当然wordpress也可以这样弄,wordpress插件很强大,有没有这样的插件呢,上网找了一下,果然有。
一款叫JSON API的wordpress插件正是我要的功能,并且更全面,它可以返回最新文章,类别,作者,文章详情,就是在wordpress中几乎所有的内容都可以通过它来获取json格式的数据,它甚至可以通过传递json数据实现文章评论、用户注册。
有了这样一款插件,关键是有了这样一个api接口,可以不用费劲自己写api了,但是可以用来做什么呢?
启用插件后,可以首先试一下
http://192.168.99.100/api/get_recent_posts/
http://192.168.99.100/api/get_post/?post_id=1
实际上,插件提供了三种api的方式:
隐式调用:
http://www.example.org/?json=1(返回该站全部json格式数据)
http://www.example.org/?p=47&json=1(返回文章id为47的json数据)
http://www.example.org/tag/banana/?json=1(返回标签是banana的json数据)
显示调用:
http://www.example.org/?json=get_recent_posts(返回最新文章json数据,默认返回很多字段,可以指定)
http://www.example.org/?json=get_post&post_id=47(返回id为47的文章json数据)
http://www.example.org/?json=get_tag_posts&tag_slug=banana(返回tag标签是banana的json数据)
链接友好型调用:
http://www.example.org/api/get_recent_posts/
http://www.example.org/api/get_post/?post_id=47
http://www.example.org/api/get_tag_posts/?tag_slug=banana
参考:
- https://wordpress.org/plugins/json-api/other_notes/
- http://www.tantengvip.com/2013/12/wordpress-api/
Woocommerce商品获取
首先在wordpress插件后台安装 WooCommerce。
WooCommerce REST API开启方式和API文档
这里摘取一些与商品相关的API,我们需要做的工作是获取商品信息而已。
(1)查看单一商品
curl https://example.com/wc-api/v3/products/546 \
-u consumer_key:consumer_secret
{
"product": {
"title": "Premium Quality",
"id": 546,
"created_at": "2015-01-22T19:46:16Z",
"updated_at": "2015-01-22T19:46:16Z",
"type": "simple",
"status": "publish",
"downloadable": false,
"virtual": false,
"permalink": "https://example.com/product/premium-quality/",
"sku": "",
"price": "21.99",
"regular_price": "21.99",
"sale_price": null,
"price_html": "<span class=\"amount\">$ 21.99</span>",
"taxable": true,
"tax_status": "taxable",
"tax_class": "",
"managing_stock": false,
"stock_quantity": 0,
"in_stock": true,
"backorders_allowed": false,
"backordered": false,
"sold_individually": false,
"purchaseable": true,
"featured": false,
"visible": true,
"catalog_visibility": "visible",
"on_sale": false,
"weight": null,
"dimensions": {
"length": "",
"width": "",
"height": "",
"unit": "cm"
},
"shipping_required": true,
"shipping_taxable": true,
"shipping_class": "",
"shipping_class_id": null,
"description": "<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>\n",
"short_description": "<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>\n",
"reviews_allowed": true,
"average_rating": "0.00",
"rating_count": 0,
"related_ids": [
37,
47,
31,
19,
22
],
"upsell_ids": [],
"cross_sell_ids": [],
"parent_id": 0,
"categories": [
"Clothing",
"T-shirts"
],
"tags": [],
"images": [
{
"id": 547,
"created_at": "2015-01-22T19:46:16Z",
"updated_at": "2015-01-22T19:46:16Z",
"src": "http://example.com/wp-content/uploads/2015/01/premium-quality-front.jpg",
"title": "",
"alt": "",
"position": 0
},
{
"id": 548,
"created_at": "2015-01-22T19:46:17Z",
"updated_at": "2015-01-22T19:46:17Z",
"src": "http://example.com/wp-content/uploads/2015/01/premium-quality-back.jpg",
"title": "",
"alt": "",
"position": 1
}
],
"featured_src": "http://example.com/wp-content/uploads/2015/01/premium-quality-front.jpg",
"attributes": [],
"downloads": [],
"download_limit": 0,
"download_expiry": 0,
"download_type": "",
"purchase_note": "",
"total_sales": 0,
"variations": [],
"parent": []
}
}
(2)查看多个商品
curl https://example.com/wc-api/v3/products \
-u consumer_key:consumer_secret
用户信息获取
这里用到的WordPress插件是JSON API User
,它允许你基于JSON API实现RESTful的用户注册、认证、密码重置、第三方登录、用户信息等功能。如果你想使用WordPress作为Mobile App的后端,那么使用它是不错的选择。
这个插件的文档可以看这里:https://wordpress.org/plugins/json-api-user/other_notes/
总体来说,就是基于WordPress的用户系统,实现了一套RESTful JSON的接口,使用token来实现权限控制与安全性。
Meteor Wordpress JSON API
这也就是Meteor中使用到的包了,Atmosphere地址如下:https://atmospherejs.com/redcap3000/wordpress-json-api。
使用它,你可以结合Wordpress JSON API plugin来获取WordPress站点的数据。
Client端使用Session订阅
创建一个main.html和一个main.js文件:
<head>
<title>testWordpress</title>
</head>
<body>
{{> wordpress_posts}}
</body>
if (Meteor.isClient) {
Session.setDefault("wp-json-api-url","http://www.mywordpresssite.com/?json=get_posts&count=10");
}
使用自定义模板
订阅wordpress
Meteor.subscribe("wordpress","http://www.mywordpresssite.com/?json=get_posts&count=10");
模板遍历wpPosts
{{#each wpPosts}}
{{{content}}}
{{/each}}
自定义结构和请求
Wordpress.find();
Wordpress.find([selector], [options])
源代码解读
首先通过Session在Meteor应用启动时设定了wp-json-api-url
。注册了一个名为wpPosts
的模板helper,如果给出id,则返回特定id的post,若没有id,则返回所有posts。
Meteor.startup(function(){
Session.setDefault('wp-json-api-url',false);
});
Handlebars.registerHelper("wpPosts",function(id){
// must provide own sub.. useful for custom templates
if(typeof id == "undefined")
return Wordpress.find();
else
return Wordpress.find({_id : id});
});
Template.wordpress_posts.onCreated(function(){
// optional if one choses to use included templates.
var self = this;
self.autorun(function () {
if(!Session.equals('wp-json-api-url',false)){
self.subscribe("wordpress", Session.get("wp-json-api-url"));
}
});
});
shared.js
创建了一个名为wordpress-json-api
的集合。
Wordpress = new Meteor.Collection("wordpress-json-api");
server.js
使用HTTP.get获取WordPress站点的数据,然后作为JSON处理。发布所有数据的发布名为wordpress
,发布dan'pian
Meteor.methods ({'callWordpress' :
// takes site WITH slash and directive .. just appends the two together
function(site,directive){
if(typeof site != "undefined" && typeof site == "string" && site != '' && typeof directive != "undefined" && typeof directive == "string" && directive != '')
var q = HTTP.get(site + directive,{headers: {"Accept":"application/json"} });
if(q.statusCode==200){
var respJson = JSON.parse(q.content);
return respJson;
}else{
return {error: q.statusCode};
}
return false;
}
});
Meteor.publish("wordpress",function(site,directive){
if(typeof site != "undefined" && typeof site == "string" && site != ''){
if(typeof directive == "undefined" || typeof directive != "string" || directive == ''){
directive = "json=get_recent_posts";
}
var q = HTTP.get(site + '?' + directive,{headers: {"Accept":"application/json"} });
if(q.statusCode==200){
var respJson = JSON.parse(q.content);
if(respJson && typeof respJson.posts != "undefined")
{
respJson.posts.filter(function(arr){
// avoid entering same id?
arr._id = arr.id + '';
if(Wordpress.findOne({_id : arr.id + ""})){
Wordpress.upsert(arr._id,arr)
}else{
Wordpress.insert(arr);
}
});
return Wordpress.find();
}else{
this.ready();
}
}else{
this.ready();
return {error: q.statusCode};
}
}
this.ready();
});
Meteor.publish("wpPost",function(id){
return Wordpress.find({_id : id + ""});
});
总结
简书真是坑,写了一大段,然后发布的时候就没了。通过历史记录也找不回来,这里重新简要写点吧。
如果你的站点主要是做内容发布,需要做Mobile端的App,则使用WordPress/Drupal/Ghost等框架作为后台和Web端,使用Meteor作为Mobile端是不错的选择。为什么不用Meteor做Web端和Mobile端呢?因为对于内容发布来说,SEO非常重要,Meteor是富前端应用,搜索引擎不能很好的检索,所以它在内容发布的优势不明显。当然移动端也可以使用Ionic、React Native等快速的构建内容阅读App。