Using WordPress ‘get_post_type()’ PHP function

The get_post_type() WordPress PHP function retrieves the post type of the current post or a given post.

Usage

get_post_type( $post );

Example:

$post_type = get_post_type( 42 ); // Retrieves the post type of the post with ID 42

Parameters

  • $post (int|WP_Post|null) – Optional. Post ID or post object. Default is global $post. Default: null

More information

See WordPress Developer Resources: get_post_type()

Examples

Check if a post is a custom post type

Check if the post with ID 42 is of type ‘custom_post_type’:

if ( get_post_type( 42 ) == 'custom_post_type' ) {
    // Do something if the post is of type 'custom_post_type'
}

Display the post type

Display the post type of the current post inside The Loop:

printf( __( 'The post type is: %s', 'textdomain' ), get_post_type() );

Get post type of the current queried object

When outside The Loop, you may need to pass get_queried_object_id() as a parameter to get the post type of the current queried object:

$current_queried_post_type = get_post_type( get_queried_object_id() );

Get the post type and run a function based on the post type

Run different functions based on the post type of the current post:

switch ( get_post_type() ) {
    case 'post':
        my_post_function();
        break;
    case 'page':
        my_page_function();
        break;
    default:
        my_default_function();
}

Filter posts based on post type

Use get_post_type() to filter posts in a custom WP_Query based on their post type:

$args = array(
    'post_type' => 'custom_post_type',
    'posts_per_page' => 10,
);
$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Display the custom_post_type content here
    }
    wp_reset_postdata();
}