post_type_exists()


WordPress関数post_type_exists()は、指定した投稿タイプが登録されているかどうかを確認するために使用されます。この関数は、カスタム投稿タイプやデフォルトの投稿タイプの有無を確認する際に便利です。

シンタックス

post_type_exists( string $post_type );
  • $post_type (string) — 確認したい投稿タイプのスラッグ。

例 1: 投稿タイプの存在確認

以下のコードは、投稿タイプが存在するかどうかを確認し、存在する場合にメッセージを表示します。

<?php
if ( post_type_exists( 'product' ) ) {
    echo 'Product投稿タイプは存在します。';
}
?>

例 2: カスタム投稿タイプの存在確認

カスタム投稿タイプeventの有無をチェックします。

<?php
if ( post_type_exists( 'event' ) ) {
    echo 'Event投稿タイプが登録されています。';
}
?>

例 3: 条件付き処理

投稿タイプが登録されている場合のみ特定の処理を実行します。

<?php
if ( post_type_exists( 'portfolio' ) ) {
    register_taxonomy( 'portfolio_category', 'portfolio', array() );
}
?>

例 4: 投稿タイプのリストを表示

登録されている投稿タイプをチェックし、リストとして出力します。

<?php
$post_types = array( 'post', 'page', 'product' );
foreach ( $post_types as $type ) {
    if ( post_type_exists( $type ) ) {
        echo $type . 'が存在します。';
    }
}
?>

例 5: 非同期リクエストでの使用

非同期リクエスト内で特定の投稿タイプの有無を確認します。

<?php
add_action( 'wp_ajax_check_post_type', function() {
    $post_type = $_GET['post_type'] ?? '';
    if ( post_type_exists( $post_type ) ) {
        wp_send_json_success( "$post_type は存在します。" );
    } else {
        wp_send_json_error( "$post_type は存在しません。" );
    }
} );
?>

注意事項

  • 指定する投稿タイプのスラッグが正確であることを確認してください。
  • カスタム投稿タイプはregister_post_type()で登録されている必要があります。

関連機能: