LoginSignup
2
4

More than 3 years have passed since last update.

WordPressでカスタマイズAPIを作る

Last updated at Posted at 2020-05-21

WordPressの記事コンテンツをAPIとして書き出すには公式同等のWP REST APIが存在します。
しかし、セキュリティ面での懸念もあり、いろいろいらない情報が書き出されてしまったり、APIの構造が複雑になったり、いろいろデメリットがあります。
固定ページの機能を活用し、スラッグAPIの固定ページを作成し、テンプレートファイルにpage-api.phpファイルを作ってしまえば、カスタマイズしたAPIを簡単に作れちゃいます。
そのコードをご紹介します。

page-api.php
<?php
// ベーシック認証
switch (true) {
    case !isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']):
    //ベーシック認証のID・PWを設定
    case $_SERVER['PHP_AUTH_USER'] !== 'user_name':
    case $_SERVER['PHP_AUTH_PW']   !== 'pass_word':
        header('WWW-Authenticate: Basic realm="Enter username and password."', true, 401);
        header('Content-Type: text/plain; charset=utf-8');
        die('認証が必要です');
}
header('content-type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");

if($_SERVER["REQUEST_METHOD"] == "GET"){
  $api_data = '[';
  if(isset($_GET['cat_api'])) {//カテゴリ指定がある場合
    $cat_id = $_GET['cat_api'];
    $posts = wp_get_recent_posts(array( 'numberposts' => 10, 'post_status' => 'publish', 'category' => $cat_id ) );//公開済みの記事を対象に
  }else{//カテゴリ指定がない場合、全記事を対象に
    $posts = wp_get_recent_posts(array( 'numberposts' => 10, 'post_status' => 'publish,private' ) );
  }
  foreach($posts as $post){
    $post_id = $post["ID"];
    $category = get_the_category($post_id);
    $cat_name = $category[0]->cat_name;
    $thumbnail = get_the_post_thumbnail_url($post_id);
    $update = get_the_modified_date("Y-m-d H:i:s", $post_id);
    $status = get_post_status($post_id);
    $post_url = '{"url":' .  site_url() . $post["post_name"] . '/",';
    $post_image = '"image":' . '"' . $thumbnail .'",';
    $post_date = '"date":' . '"' . $post["post_date"] . '",';
    $post_update = '"update":' . '"' . $update . '",';
    $post_status = '"status":' . '"' . $status . '",';
    $post_category = '"category":' . '"' . $cat_name . '",';
    $post_title = '"title":' . '"' . $post["post_title"] . '",';
    $post_excerpt = '"expert":' . '"' . $post["post_excerpt"] . '",';
    $post_content = $post["post_content"];
    $post_content = wpautop($post_content); //余計な改行等々
    // 関連記事のデータ生成
    $relateds = wp_get_recent_posts(array( 'numberposts' => 3, 'post_status' => 'publish', 'category' => $category_id ) );
    $post_related = '<h2>関連記事</h2><ul>';
    foreach($relateds as $related){
        $related_id = $related["ID"];
        $post_related .= '<li><a href="' . site_url() . $related["post_name"] . '/">' . $related["post_title"] . '</li>';
    }
    $post_related .= '</ul>';
    $post_content .= $post_related;
    $post_content = str_replace('"', '\"', $post_content);
    $post_content = '"content":' . '"' . $post_content . '"},';
    $api_data = $api_data . $post_url . $post_image . $post_date . $post_update . $post_status . $post_category . $post_title . $post_excerpt . $post_content;
  }
  $api_data = $api_data . ']';
  $api_data = preg_replace('/(?:\n|\r|\r\n)/', '', $api_data ); //余計なものを一括置換
  $api_data = str_replace('},]', '}]', $api_data);
  $api_data = str_replace(' ', '', $api_data);
  print $api_data;
}else{
  header("HTTP/1.0 404 Not Found");
  return;
}


2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4