post_type_exists() の使い方|説明・引数・注意点

説明

post_type_exists() は、指定した投稿タイプが登録されているかを調べる関数です。

基本構文

post_type_exists( string $post_type ): bool

引数

  • $post_type:投稿タイプ名

戻り値

登録されていれば true。

使い方(サンプル)

if ( ! post_type_exists( 'news' ) ) {
	// 登録されていない
}

注意点

  • init より前に呼ぶと false になります。

実務での使いどころ

  • 投稿タイプが登録されているかを、確認してから使うとき。
  • 他のプラグインが登録する、投稿タイプを、あるときだけ使うとき。

よくあるミスと対処

  • init フックより前に呼び、まだ登録されておらず false になる。
  • スラッグではなく、表示名を渡している。

NG例

if ( post_type_exists( 'news' ) ) { // init より前に呼ぶと false
	// ...
}

OK例

add_action( 'init', function () {
	if ( post_type_exists( 'news' ) ) {
		// ...
	}
}, 20 );

使い分け早見表

やりたいこと 使うもの
投稿タイプがあるか確認 post_type_exists()
投稿タイプの情報を取得 get_post_type_object()
投稿タイプの一覧を取得 get_post_types()

関連項目

register_post_type()、get_post_types()、get_post_type_object()

公式リファレンス:post_type_exists() | Function | WordPress Developer Resources

コメント

タイトルとURLをコピーしました