0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Wordpressのfunction.phpのメモ

Posted at
// メインクエリの実行前に投稿一覧の取得条件をカスタマイズできるフック
add_action( 'pre_get_posts', function( $query ) {
	
  // サブルーチンとしてローカル関数を用意
  $get_my_post_types = function($exclude = array()) {
    $custom = get_post_types( array('public' => true, '_builtin' => false), 'names' );
    return array_merge( array('post'), array_diff( $custom, $exclude ) );
  };

  if ( is_admin() || ! $query->is_main_query() ) return;

  // カテゴリアーカイブ
  if ( $query->is_category() ) {
    $exclude = array();
    $query->set( 'post_type', $get_my_post_types($exclude) );
  }

  // タグアーカイブ
  if ( $query->is_tag() ) {
    $exclude = array();
    $query->set( 'post_type', $get_my_post_types($exclude) );
  }

  // トップページ
  if ( is_home() ) {
	  $exclude = array();
	  $query->set( 'post_type', $get_my_post_types($exclude) );
  }
});


✅ 投稿一覧にカスタム投稿タイプを含めるためのフィルター


📌 コードの意味を簡単に分解すると:

$get_my_post_types = function($exclude = array()) {
    $custom = get_post_types( array('public' => true, '_builtin' => false), 'names' );
    return array_merge( array('post'), array_diff( $custom, $exclude ) );
};
  • public かつ builtin でない投稿タイプ(≒自分で作ったCPT)を取得
  • post(通常投稿)と一緒に返す

💡 そして is_home()is_category() のときに:

$query->set( 'post_type', $get_my_post_types($exclude) );
  • 投稿タイプの絞り込みを変更(例:post, youtube, news など複数)
  • つまり「ホーム」や「カテゴリ」で、通常投稿だけでなくCPTも出すようにしているということです

🔎 このコードは REST API には影響しません

なぜなら:

  • pre_get_posts はあくまで「クエリをベースにした画面描画(HTML)」用
  • REST API は WP_REST_*_Controller が使う get_items() メソッドなどでクエリ生成するため、このフックは無視される

✅ まとめ

このコードは REST APIとは無関係で、ブラウザからの表示時のカスタマイズです。
いま直面している API経由でpost_statusが「publish」以外含まれない問題とは関係ありません。

引き続き、rest_api_init + rest_post_statusesrest_{post_type}_query の組み合わせで、API挙動側をチューニングする必要があります。


ご希望があれば、この pre_get_posts を「管理画面でも有効」「REST APIにも類似ロジック適用」などに拡張するコード例もご案内できます。お気軽にどうぞ。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?