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

前端之家收集整理的这篇文章主要介绍了在我的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

原文链接:https://www.f2er.com/android/317194.html

猜你在找的Android相关文章