WordPress: Check if it’s a Post or a Page


Categories
Tags
Are you looping through/listing posts and pages or building templates and need to know what’s a post and what’s a page? Here are some possible answers.

When inside the loop, a simple if statement should suffice:

if (get_post_type() === 'post') {
    //post
}

if (get_post_type() === 'page') {
    //page
}

Outside of the loop, you might need to acquire the page/post id from the global post object first, and pass that to the get_post_type() functions:

$id = get_the_id(); //current post/page id
if (get_post_type($id) === 'post') {
    //post
}

if (get_post_type($id) === 'page') {
    //page
}

Similarly, you can use the is_page() and is_single() functions to the same end. This is possibly the better choice, since it’s a simple true or false check rather than a check against a string value:

$id = get_the_id(); //current post/page id
if (is_page($id) ){
	//page
}
if (is_single($id) ){
	//post
}

Comments

Whether you have feedback, a question, want to share your opinion, or simply want to say thank you - we welcome comments! Please read the disclaimer.

Disclaimer and Legal Information

The use of any content found on or via this website (code, how to guides etc.) is done so at your own risk. We take no responsibility for any issues encountered.

This blog and its authors will not be held responsible for any misuse, reuse, recycled and cited/uncited copies of content from this website by others.

The views and opinions expressed in this blog are those of the author(s) and do not necessarily reflect the position or opinion of any other agency, organisation, employer or company.

Comments are moderated but we do not take any responsibility for any libel or litigation that results from something written in a comment. We reserve the right to reject or delete any comment for any reason whatsoever (abusive, profane, rude etc). Please keep your comments polite and relevant.

We are happy for you to quote and share our content in any reasonable manner, e.g. post links to our blogs on social media, but not in any way that suggests that we, or our authors, endorse you, your use or your views. Nothing negative please.

We appreciate attributions, e.g. a link to our website (www.dragoncode.co.uk).

Thank you – we hope you find the website useful.