てくてくあるく

WordPress の テーマ とか プラグイン に ついて 勉強しています

元々 使いやすい WP Rest Api ですが
自分が よく使うパターンで class 化 しました


データは 自分が よく使うものに 絞ってしまっていますので
使いやすいように 改造していただければ…

sticky 周りは 結構雑で あれ?? 投稿が 表示されない… なんて 事が起きたら 多分 ココを 最初に考えたら良いと思います

まだ 深く使ってないので エラーがあるかもしれませんが ざっと こんな感じです

コメントもついてないので 読みにくいと思います… (スミマセン)

//--------------------------------------------------------------------------------------------------
//  Rest Api 用
//--------------------------------------------------------------------------------------------------

if( ! class_exists( 'jr_get_contents' ) ) {
  class jr_get_contents {

    public $cache_dir, $cache_time;

    function __construct() {
      $this->set_cache_dir();
      $this->set_cache_time();
    }

    function set_cache_dir( $cache_dir = null ) {
      if( ! empty( $cache_dir ) ) {
        $this->cache_dir = realpath( $cache_dir );
      }
      if( empty( $this->cache_dir ) ) {
        $this->cache_dir = realpath( __DIR__ . '/jr_get_contents_cache' );
      }
    }

    function set_cache_time( $cache_time = null ) {
      if( ! empty( $cache_time ) && is_numeric( $cache_time ) ) {
        $this->cache_time = intval( $cache_time );
      } else {
        $this->cache_time = 60 * 30; // 30min
      }
    }

//--------------------------------------------------------------------------------------------------

    function get_contents( String $url, String $extension = 'cache' ) {
      if( empty( $extension ) )
        $extension = 'cache';

      $cache_dir = $this->cache_dir;
      $cache_name = hash( 'md5', $url ) . '.' . $extension;

      $cache_path = $cache_dir . DIRECTORY_SEPARATOR . $cache_name;
      if( $this->is_cache( $cache_path ) ) {
        $contents = file_get_contents( $cache_path );
      } else {
        $curl_option = [
          CURLOPT_TIMEOUT        => 5,
          CURLOPT_RETURNTRANSFER => true,
        ];

        if( ! empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
          $curl_option[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
        }

        $curl = curl_init( $url );
        curl_setopt_array( $curl, $curl_option );
        $contents = curl_exec( $curl );
        $info     = curl_getinfo( $curl );
        $error    = curl_errno( $curl );

        if( $info['http_code'] !== 200 && $error !== CURLE_OK ) {
          $contents = false;
        }

        if( $contents !== false ) {
          $this->save_cache( $cache_path, $contents );
        }

        curl_close( $curl );
      }

      if( $this->is_json( $contents ) ) {
        $contents = json_decode( $contents, true );
      }

      return $contents;
    }

    function is_cache( $cache_path ) {
      if( is_file( $cache_path ) ) {
        $cache_time = $this->cache_time;
        $time = filemtime( $cache_path );
        if( time() - $time <= $cache_time ) {
          return true;
        }
      }
      return false;
    }

    function save_cache( $cache_path, $contents ) {
      $result = file_put_contents( $cache_path, $contents, LOCK_EX );
      if( $result !== false ) {
        chmod( $cache_path, 0666 );
      }
      return $result;
    }

    function is_json( $contents ) {
      return is_string( $contents ) && is_array( json_decode( $contents, true ) ) && ( json_last_error() == JSON_ERROR_NONE ) ? true : false;
    }

//--------------------------------------------------------------------------------------------------

    function get_wp_rest_api( $api_url, $echo_self = false, $echo_sticky = false, Array $sticky_id = null ) {
      $return_posts = [];

      $sticky_posts = [];
      $normal_posts = [];

      if( ! is_array( $api_url ) ) {
        if( ! empty( $sticky_id ) ) {
          $sticky_id = [ $api_url => $sticky_id ];
        }
        $api_url = [ $api_url ];
      }

      foreach( $api_url as $url ) {
        $contents = $this->get_contents( $url, 'json' );

        if( ! is_array( $contents ) )
          return false;

        foreach( $contents as $row ) {

          // コアに組み込まれる前 (プラグイン)
          if( isset( $row['ID'] ) ) {

            // Thumbnail
            $thumbnail = '';
            if( empty( $thumbnail ) && isset( $row['featured_image']['attachment_meta']['sizes']['medium']['url'] ) ) {
              $thumbnail = $row['featured_image']['attachment_meta']['sizes']['medium']['url'];
            }
            if( empty( $thumbnail ) && isset( $row['featured_image']['attachment_meta']['sizes']['thumbnail']['url'] ) ) {
              $thumbnail = $row['featured_image']['attachment_meta']['sizes']['thumbnail']['url'];
            }
            if( empty( $thumbnail ) && isset( $row['featured_image']['attachment_meta']['sizes']['full']['url'] ) ) {
              $thumbnail = $row['featured_image']['attachment_meta']['sizes']['full']['url'];
            }
            if( empty( $thumbnail ) && isset( $row['featured_image']['source'] ) ) {
              $thumbnail = $row['featured_image']['source'];
            }
            if( empty( $thumbnail ) ) {
              $thumbnail = '/resources/images/base/image.svg';
            }

            $post = [
              'id'        => $row['ID'],
              'title'     => $row['title'],
              'content'   => $row['content'],
              'excerpt'   => $row['excerpt'],

              'image'     => $thumbnail,
              'date'      => new DateTime( $row['date'] ),
              'modified'  => new DateTime( $row['modified'] ),
              'slug'      => $row['slug'],
              'link'      => $row['link'],
              'guid'      => $row['guid'],

              'class'     => [],
            ];

            // Author
            $post['author'] = [
              'id'          => $row['author']['ID'],
              'username'    => $row['author']['username'],

              'name'        => $row['author']['name'],
              'first_name'  => $row['author']['first_name'],
              'last_name'   => $row['author']['last_name'],

              'nickname'    => $row['author']['nickname'],

              'slug'        => $row['author']['slug'],
            ];

          // コアに組み込まれた後
          } else {

            // Thumbnail
            $thumbnail = '';
            if( empty( $thumbnail ) && isset( $row['_embedded']['wp:featuredmedia'][0]['media_details']['sizes']['medium']['source_url'] ) ) {
              $thumbnail = $row['_embedded']['wp:featuredmedia'][0]['media_details']['sizes']['medium']['source_url'];
            }
            if( empty( $thumbnail ) && isset( $row['_embedded']['wp:featuredmedia'][0]['media_details']['sizes']['thumbnail']['source_url'] ) ) {
              $thumbnail = $row['_embedded']['wp:featuredmedia'][0]['media_details']['sizes']['thumbnail']['source_url'];
            }
            if( empty( $thumbnail ) && isset( $row['_embedded']['wp:featuredmedia'][0]['media_details']['sizes']['full']['source_url'] ) ) {
              $thumbnail = $row['_embedded']['wp:featuredmedia'][0]['media_details']['sizes']['full']['source_url'];
            }
            if( empty( $thumbnail ) && isset( $row['_embedded']['wp:featuredmedia'][0]['source_url'] ) ) {
              $thumbnail = $row['_embedded']['wp:featuredmedia'][0]['source_url'];
            }
            if( empty( $thumbnail ) ) {
              $thumbnail = '/resources/images/base/image.svg';
            }

            $post = [
              'id'        => $row['id'],
              'title'     => $row['title']['rendered'],
              'content'   => $row['content']['rendered'],
              'excerpt'   => $row['excerpt']['rendered'],

              'image'     => $thumbnail,
              'date'      => new DateTime( $row['date'] ),
              'modified'  => new DateTime( $row['modified'] ),
              'slug'      => $row['slug'],
              'link'      => $row['link'],
              'guid'      => $row['guid']['rendered'],

              'class'     => [],
            ];

            // Author
            if( ! empty( $row['_embedded'] ) ) {
              $post['author'] = [
                'id'          => empty( $row['_embedded']['author'][0]['id'] ) ? '' : $row['_embedded']['author'][0]['id'],
                'username'    => empty( $row['_embedded']['author'][0]['username'] ) ? '' : $row['_embedded']['author'][0]['username'],

                'name'        => empty( $row['_embedded']['author'][0]['name'] ) ? '' : $row['_embedded']['author'][0]['name'],
                'first_name'  => empty( $row['_embedded']['author'][0]['first_name'] ) ? '' : $row['_embedded']['author'][0]['first_name'],
                'last_name'   => empty( $row['_embedded']['author'][0]['last_name'] ) ? '' : $row['_embedded']['author'][0]['last_name'],

                'nickname'    => empty( $row['_embedded']['author'][0]['nickname'] ) ? '' : $row['_embedded']['author'][0]['nickname'],

                'slug'        => empty( $row['_embedded']['author'][0]['slug'] ) ? '' : $row['_embedded']['author'][0]['slug'],
              ];
            }

          }

          // Is Sticky
          if( $row['sticky'] ) {
            $post['class'][] = 'sticky';
          }
          if( ! $row['sticky'] && ! empty( $sticky_post_id[$url] ) && in_array( $row['id'], $sticky_post_id[$url] ) ) {
            $post['class'][] = 'sticky';
          }

          // Set Post
          if( in_array( 'sticky', $post['class'] ) ) {
            $sticky_posts[$post['date']->format('U')] = $post;
          } else {
            $normal_posts[$post['date']->format('U')] = $post;
          }
        }
      }

      if( function_exists( 'get_posts' ) && $echo_self ) {
        $self_posts = get_posts( ['posts_per_page' => -1] );
        foreach( $self_posts as $posts ) {

          // Thumbnail
          $thumbnail = '';
          $thumbnail = get_the_post_thumbnail_url( $posts->ID, 'medium' );
          if( empty( $thumbnail ) ) {
            $thumbnail = '/resources/images/base/image.svg';
          }

          $post = [
            'id'        => $posts->ID,
            'title'     => apply_filters( 'the_title', $posts->post_title ),
            'content'   => apply_filters( 'the_content', $posts->post_content ),
            'excerpt'   => $this->get_excerpt( $posts->post_excerpt, $posts->post_content ),

            'image'     => $thumbnail,
            'date'      => new DateTime( $posts->post_date ),
            'modified'  => new DateTime( $posts->post_modified ),
            'slug'      => $posts->post_name,
            'link'      => get_permalink( $posts->ID ),
            'guid'      => $posts->guid,

            'class'     => [],
          ];

          // Author
          $post['author'] = [
            'id'          => get_the_author_meta( 'ID', $posts->post_author ),
            'username'    => get_the_author_meta( 'user_login', $posts->post_author ),

            'name'        => get_the_author_meta( 'display_name', $posts->post_author ),
            'first_name'  => get_the_author_meta( 'first_name', $posts->post_author ),
            'last_name'   => get_the_author_meta( 'last_name', $posts->post_author ),

            'nickname'    => get_the_author_meta( 'nickname', $posts->post_author ),

            'slug'        => '',
          ];

          // Is Sticky
          if( $posts->sticky ) {
            $post['class'][] = 'sticky';
          }

          // Set Post
          if( in_array( 'sticky', $post['class'] ) ) {
            $sticky_posts[$post['date']->format('U')] = $post;
          } else {
            $normal_posts[$post['date']->format('U')] = $post;
          }
        }
      }

      krsort( $sticky_posts );
      krsort( $normal_posts );

      if( $echo_sticky && ! empty( $sticky_posts ) ) {
        $return_posts = array_merge( $sticky_posts, $normal_posts );
      } else {
        $return_posts = $normal_posts;
      }

      return $return_posts;
    }

    /* wp_trim_excerpt を 参考 に */
    function get_excerpt( $excerpt = false, $content = false ) {
      $return = $excerpt;
      if( function_exists( 'strip_shortcodes' ) && function_exists( 'apply_filters' ) && function_exists( 'wp_trim_words' ) ) {
        if ( empty( $excerpt ) && ! empty( $content ) ) {
          $text = $content;
          $text = strip_shortcodes( $text );
          $text = apply_filters( 'the_content', $text );
          $text = str_replace( ']]>', ']]&gt;', $text );

          $excerpt_length = apply_filters( 'excerpt_length', 55 );
          $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
          $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );

          $return = $text;
        }
      }
      return $return;
    }

  }
}

何度も API を 読みに行くと 負荷が高くなってしまうかな?? なんて 考えたので 30分の間 キャッシュしています
(使う時は 環境に合わせて変えてください : $this->cache_time = 60 * 30;)

キャッシュする場所は ファイルがある場所の jr_get_contents_cache という ディレクトリ以下 に 作成します
(使う時は 環境に合わせて変えてください : $this->cache_dir = realpath( __DIR__ . ‘/jr_get_contents_cache’ );)

ファイルは chmod で 666 に していますので 書き換えてください
(使う時は 環境に合わせて変えてください : chmod( $cache_path, 0666 );)

データの取得は cURL を 使っています
(タイムアウトは 5秒 です : $curl_option あたり)


使い方は そのまま 使う場合 は

function get_campaign_post() {
  $ary_api_url = array(
    ( is_ssl() ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'] . "/wp-json/wp/v2/posts?_embed&per_page=20",
  );

  $api_object = new jr_get_contents;
  $api_posts = $api_object->get_wp_rest_api( $ary_api_url );

  return $api_posts;
}

みたいな感じで 使用します


タグ等で 絞りたい場合は ID が 分かれば 基本的な ルールに則って URLを 変更すればよいのですが スラッグを 使用するのであれば 取得元に プラグインを 入れると 使いやすくなります

私は WP REST API filter parameter という プラグインを使用しています

WP-API/rest-filter: Restores the `filter` param to post enpdpoints.
https://github.com/WP-API/rest-filter

WP REST Filter を 使っても 問題ないかもしれません
(試していないため エラーが出るかもしれません)

WP REST Filter
https://wordpress.org/plugins/wp-rest-filter/
function get_campaign_post() {
  $tag_name = 'campaign-1887';

  $ary_api_url = array(
    ( is_ssl() ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'] . "/wp-json/wp/v2/posts?_embed&per_page=20&filter[tag]={$tag_name}",
  );

  $api_object = new jr_get_contents;
  $api_posts = $api_object->get_wp_rest_api( $ary_api_url, true );

  return $api_posts;
}

みたいな感じで 取得できるようになるかと思います


使い所は限られるかもしれないけど カスタマイズして 使ってみてください

エラー報告 お待ちしております!!

Related Article

PageSpeed Insights から あまり良い評価が得られなかったのは 別の原因があった…

詳細へ »