Getting the post type of a WordPress post using get_post_type

The WordPress get_post_type function retrieves the post type of a specified post. This can be useful when you need to determine the type of content you are working with, such as a post, page, or custom post type.

By using get_post_type, you can easily customize the behavior of your WordPress site based on the type of content being displayed, allowing for more dynamic and targeted functionality.

Parameters accepted by get_post_type function

  • $post (int|WP_Post|null): This parameter is optional and its default value is null. It represents the Post ID or post object. If no value is provided, the function will use the global $post variable by default.

Value returned by get_post_type function

The function returns a string representing the post type on success. If the function fails to retrieve the post type, it returns false.

Examples

How to get the post type of a specific post

Use the get_post_type function to retrieve the post type of a specific post.

$post_id = 123;
$post_type = get_post_type($post_id);
echo $post_type;

How to check if the post type is ‘page’

Use the get_post_type function to check if the post type of the current post is ‘page’.

$post_type = get_post_type();
if ($post_type === 'page') {
 echo 'This is a page.';
} else {
 echo 'This is not a page.';
}

How to display different content based on post type

Use the get_post_type function to display different content based on the post type of the current post.

$post_type = get_post_type();
if ($post_type === 'post') {
 echo 'This is a blog post.';
} elseif ($post_type === 'page') {
 echo 'This is a page.';
} else {
 echo 'This is a custom post type.';
}

Conclusion

In conclusion, the get_post_type function is an essential component for retrieving the post type of a given post. It allows developers to easily access and manipulate the post type data, providing flexibility and control over the content displayed on their WordPress websites. By understanding how to use this function effectively, developers can enhance the functionality and user experience of their websites. With its simple syntax and wide range of applications, the get_post_type function is an essential tool for any WordPress developer.

Related WordPress Functions