Hey everyone,
I’m working on a WordPress project and I’m stuck on something. Does anyone know how to figure out if a piece of content is a regular post or a static page?
I’ve been digging through the WordPress docs but can’t seem to find a straightforward way to do this. It would be super helpful if there’s a built-in function or some kind of check we can use.
Here’s a bit of code I’ve tried, but it’s not working:
function is_it_post_or_page($content_id) {
if (get_post_type($content_id) == 'post') {
return 'This is a post';
} elseif (get_post_type($content_id) == 'page') {
return 'This is a page';
} else {
return 'Unknown content type';
}
}
Any ideas on how to make this work or if there’s a better way to do it? Thanks in advance for any help!
Your approach is sound, but there’s a more efficient way to handle this. Instead of using if-else statements, you can leverage WordPress’s built-in functions is_singular(‘post’) and is_singular(‘page’). These functions are specifically designed for this purpose and provide better performance. Here’s an example:
function determine_content_type() {
if (is_singular('post')) {
return 'This is a post';
} elseif (is_singular('page')) {
return 'This is a page';
} else {
return 'This is a ' + get_post_type();
}
}
This method is more robust and will work correctly even if you’re using custom post types. It’s also worth noting that these functions automatically use the current post in the loop, so you don’t need to pass an ID parameter.
I’ve faced this exact issue before, and I can tell you that your approach is on the right track.
The get_post_type() function is indeed the way to go. However, there’s a slight tweak you need to apply for it to work as expected.
Instead of comparing the result to strings ‘post’ and ‘page’, you should store the result in a variable and then check it. For example:
function is_it_post_or_page($content_id) {
$post_type = get_post_type($content_id);
if ($post_type === 'post') {
return 'This is a post';
} elseif ($post_type === 'page') {
return 'This is a page';
} else {
return 'This is a ' . $post_type;
}
}
This modification should resolve the issue. Also, if you’re within the WordPress loop, consider using is_single() and is_page() for more contextual checks. Hopefully, this insight helps you move forward!
hey josephk, ur code looks good! just a quick tip - try using === instead of == for stricter comparison. also, u can simplify it by returning the post type directly:
function is_it_post_or_page($content_id) {
return 'This is a ' . get_post_type($content_id);
}
hope this helps!