Meteor开发指南 — 连接WordPress应用(一)

背景

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了。

Kitematic
WordPress安装界面

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

参考:

  1. https://wordpress.org/plugins/json-api/other_notes/
  2. 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。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容