DigiPress

Highly Flexible WordPress Theme

[WP]getEntityRecords のパラメータの種類と独自フィールドの追加方法

カスタマイズ・技術情報

WordPress では、複数の投稿データ(リスト)を取得する場合は getEntityRecords 、単一の投稿データを取得する場合はgetEntityRecord という便利な API が用意されています。

例えば Gutenberg のブロック開発では、この API を利用することで、指定した条件に合致する投稿の一覧を表示するカスタムブロックを作成できます。

getEntityRecords で指定できるパラメータ(クエリ)

getEntityRecords 関数を使用してJavaScript(React) 経由で WordPress の記事一覧を抽出する場合、getEntityRecords の実態は WordPress の REST API を使用してエンティティを作成しているため、抽出条件を指定する各パラメータは、WordPress の REST API (/wp-json/wp/v2/posts) で指定可能なパラメータと共通しています。

参考 : https://developer.wordpress.org/rest-api/reference/posts/#arguments

このうち、記事を取得する対象期間を指定するためのafter(指定日時より後を対象), before(指定日時より前を対象) パラメータを指定する場合、値には ISO8601 形式に準拠するフォーマットの日付用文字列を与える必要があります。
ISO8601 形式とは、日付と時刻をセパレータ「T」で区切って YYYY-MM-DDThh:mm:ss という書式に変換された文字列です。

最も簡単に ISO8601 形式に近い書式を得るには、日付と時刻を文字列型に変換する toLocaleString メソッドにスウェーデンのロケール( sv-SE )を指定すると便利です。

new Date().toLocaleString( 'sv-SE' ).replace( ' ', 'T' )

例えば、2030年4月25日20時1分45秒であれば、「2030-04-25T20:01:45」というフォーマットに変換した日付の文字列を before, after, modified_before または modified_after の値として指定します。

getEntityRecord で取得できる投稿データ

getEntityRecord関数 (WordPress の REST API) を使用して投稿データを取得した場合、デフォルトでは以下のフィールドが含まれます。

デフォルトのフィールド

id (数値)

投稿のID。

  1. 12
date (文字列)

投稿の日付。

  1. "2024-01-30T10:20:00"
date_gmt (文字列)

GMTでの投稿日付。

  1. "2024-01-30T01:20:00"
guid (オブジェクト)

投稿のGUID。

  1. {
  2. "raw": "http://wpthemetestdata.wordpress.com/2024/01/01/post-title/",
  3. "rendered": "http://wpthemetestdata.wordpress.com/2024/01/01/post-title/"
  4. }
modified (文字列)

投稿が最後に変更された日付。

  1. "2024-03-30T10:20:00"
modified_gmt (文字列)

GMTでの最終変更日。

  1. "2024-03-30T01:20:00"
slug (文字列)

投稿のスラッグ。

  1. "post-title"
status (文字列)

投稿のステータス(”publish”、”pending”、”draft” など)。

  1. "publish"
type (文字列)

投稿タイプ(”post”、”page” など)。

  1. "post"
link (文字列)

投稿のパーマリンク。

  1. "https://mywebsite.com/archives/12286"
title (文字列)

投稿のタイトル。

  1. {
  2. "raw": "投稿タイトル",
  3. "rendered": "投稿タイトル"
  4. }
content (オブジェクト)

投稿の本文。

  1. {
  2. "raw": "<!-- wp:paragraph -->\n<p class=\"\">投稿の本文。</p>\n<!-- /wp:paragraph -->",
  3. "rendered": "\n<p class=\"\" data-block-type=\"core\">投稿の本文。</p>\n",
  4. "protected": false,
  5. "block_version": 1
  6. }
excerpt (オブジェクト)

投稿の抜粋。

  1. {
  2. "raw": "これは抜粋文です。",
  3. "rendered": "これは抜粋文です。",
  4. "protected": false
  5. }
author (数値)

投稿の寄稿者ID。

  1. 2
featured_media (数値)

アイキャッチ画像(投稿サムネイル)のID。

  1. 2
comment_status (文字列)

コメント受付可否のステータス(”open”または”closed”)。

  1. "open"
ping_status (文字列)

Ping 受付可否のステータス(”open”または”closed”)。

  1. "closed"
sticky (論理値)

投稿が先頭固定表示に指定されているかどうか( true または false )。

  1. false
template (文字列)

投稿のテンプレート。

  1. "custom-templpate"
format (文字列)

投稿のフォーマット。

  1. "status"
meta (オブジェクト)

投稿のメタデータ。

  1. {
  2. "foot_notes": "",
  3. "_wp_rev_ctl_limit": ""
  4. }
categories (配列)

投稿のカテゴリーID。

  1. [ 4, 6, 8 ]
tags (配列)

投稿に付けられたタグのID。

  1. [ 12, 20, 22 ]

参考 : https://developer.wordpress.org/rest-api/reference/posts/#schema

これらのフィールドは、投稿タイプが post の場合のものとなり、カスタム投稿タイプやページには、これらのフィールドの一部が含まれない場合があります。

独自のフィールドを追加する

先述のデフォルトのフィールドでは、例えばカテゴリ名や寄稿者名、コメント数、アイキャッチ画像(投稿サムネイル)のURLが含まれないため、getEntityRecord 関数を利用して一般的なアーカイブページのような、アイキャッチ画像、タイトル、カテゴリ名、メタ情報などが並んだ投稿リストを表示する場合、情報が不足しています。

これを補うには、PHP にてフィールドを追加するためのregister_rest_field という関数を利用をして、必要な投稿データを取得する処理(関数)を、rest_api_init というアクションフィルターにフックすることで、getEntityRecord から取得される投稿データに目的のデータを値に持つ独自のフィールドを追加しておくことで対応できます。

例えば、アイキャッチ画像を JavaScript(React)から PHP(REST API) で取得してその結果を受け取りたい場合は、以下のように REST API を登録しておきます。

PHP
  1. // 投稿サムネイル(アイキャッチ)を取得するための関数を登録
  2. function myplugin_register_rest_fields() {
  3. register_rest_field( 'post',
  4. 'post_image_url', // 追加するフィールド名
  5. array(
  6. 'get_callback' => 'mytheme_get_post_image_url', // コールバック関数
  7. 'update_callback' => null,
  8. 'schema' => null,
  9. ) );
  10. }
  11. add_action( 'rest_api_init', 'myplugin_register_rest_fields' );
  12.  
  13. // 投稿サムネイルを取得するコールバック関数(フィールドに渡す値を返す)
  14. function myplugin_get_post_image_url( $post ) {
  15. if ( has_post_thumbnail( $post[ 'id' ] ) ) {
  16. // アイキャッチ画像のデータを取得
  17. $img_urls = wp_get_attachment_image_src( get_post_thumbnail_id( $post[ 'id' ] ), 'full' );
  18. // フルサイズの画像(URL)を返す
  19. return $img_urls[0];
  20. }
  21. return false;
  22. }

これで post_image_url というカスタムフィールドが投稿データに追加されました。
これにより、JavaScript から getEntityRecordsgetEntityRecord で抽出した記事一覧(配列)の各投稿データについて、追加したカスタムフィールド( post_image_url )を参照することでアイキャッチ画像のURLを受け取ることができます。

JavaScript(React)
  1. import { useSelect } from "@wordpress/data";
  2.  
  3. // 記事一覧を取得する関数
  4. const getPostsByQuery = ( props ) => {
  5. const {
  6. query,
  7. postType
  8. } = props;
  9.  
  10. const filteredPosts = useSelect( ( select ) => {
  11. const { getEntityRecords } = select( 'core' );
  12. return getEntityRecords( 'postType', postType, query );
  13. } );
  14.  
  15. return filteredPosts;
  16. }
  17.  
  18. // クエリパラメータ例
  19. const query = {
  20. orderby: 'modified', // 並び順
  21. per_page: 10, // 記事取得数
  22. author: 1, // 対象の寄稿者(ID)
  23. search: "Gutenberg", // 検索ワード
  24. categories: [ 4, 12, 20 ] // 対象カテゴリ(ID)
  25. };
  26.  
  27. // クエリパラメータを元に記事一覧を取得(対象投稿タイプ: post )
  28. const posts = getPostsByQuery( { query, postType: 'post' } );
  29.  
  30. if ( posts && Array.isArray( posts ) ) {
  31. posts.forEach( ( post, index ) => {
  32. // post.post_image_url を参照するとアイキャッチ画像のURLが得られる
  33. console.dir( post.post_image_url );
  34. } )
  35. }

同様に、PHP にて register_rest_field で JavaScript から参照したい投稿のデータを渡すカスタムフィールドを登録しておくことで、例えば寄稿者の細かなプロフィール情報やカテゴリーリンクのリストなど、デフォルトのフィールドでは取得できない不足しているデータを getEntityRecordsgetEntityRecord の API を介して JavaScript で扱えるようになります。

Share / Subscribe
Facebook Likes
Posts
Hatena Bookmarks
Pinterest
Pocket
Feedly
Send to LINE