在我的Android应用程序中从WordPress获取帖子

我是 Android开发的新手,我正在尝试创建一个只显示WordPress网站上的帖子类别和帖子的应用程序.请帮助我.

解决方法

您要做的是从WordPress创建某种REST API,以返回对您的Android HTTP请求的JSON响应.要做到这一点,首先针对Android,您可以参考这篇文章:

Make an HTTP request with android

然后,对于服务器端(您的WordPress),您将不得不添加一个插件来处理您的API请求.为此,在wp-content / plugins中创建一个名为api-endpoint.php的文件,并使用如下内容:

<?php

class API_Endpoint{

 /** Hook WordPress
 *  @return void
 */
 public function __construct(){
    //Ensure the $wp_rewrite global is loaded

    add_filter('query_vars',array($this,'add_query_vars'),0);
    add_action('parse_request','sniff_requests'),0);
    add_action('init','add_endpoints'),0);
}   

  /**
      * Add public query vars
  * @param array $vars List of current public query vars
  * @return array $vars 
  */
 public function add_query_vars($vars){
    $vars[] = '__api';
    return $vars;
 }

 /** 
     * Add API Endpoints
 *  Regex for rewrites - these are all your endpoints
 *  @return void
 */
 public function add_endpoints(){
    //Get videos by category - as an example
    add_rewrite_rule('^api/videos/?([0-9]+)?/?','index.php?__api=1&videos_cat=$matches[1]','top');

    //Get products - as an example
    add_rewrite_rule('^api/product/?([0-9]+)?/?','index.php?__api=1&product=$matches[1]','top');
 }

  /**   Sniff Requests
  * This is where we hijack all API requests
  *     If $_GET['__api'] is set,we kill WP and serve up rss
  * @return die if API request
  */
 public function sniff_requests(){
    global $wp;

    if(isset($wp->query_vars['__api'])){
        $this->handle_api_request();
        exit;
    }

 }

/** Handle API Requests
 *  This is where we handle off API requests
 *  and return proper responses
 *  @return void
 */
 protected function handle_api_request(){
    global $wp;
    /**
    *
    * Do your magic here ie: fetch from DB etc
    * then get your $result
    */

    $this->send_response($result);
 }



 /** Response Handler
 *  This sends a JSON response to the browser
 */
 protected function send_response(array $data){
    header('content-type: application/json; charset=utf-8');
    echo json_encode($data);
    exit;
 }



}
new API_Endpoint();

然后通过WordPress管理界面启用API_Endpoint插件,不要忘记刷新永久链接.

之后,您将能够向以下位置发出API请求:

http://example.com/api/videos/12

要么

http://example.com/api/product/4

编辑

以获取WordPress类别为例 – http://codex.wordpress.org/Function_Reference/get_categories

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...