I'm using a loop in my search.php file to loop through the results and display their title.
This works great, but I'd like to check for each result, whether it is a page or a post. The following code doesn't seem to work.
if ( have_posts() ) : ?>
<h1 class="page-title"><?php printf( __( 'Results for: %s', 'domain' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
<?php while ( have_posts() ) : the_post();
$title = get_the_title();
echo '<article class="post-card">';
if ( is_page() ) {
echo 'page';
} else if ( is_singular('post') ) {
echo 'post';
}
echo '<h2>' .$title. '</h2>';
echo '</article>';
endwhile; ?>
<?php endif;
I think you are looking for this function. Will be shorter. Just pass the post object and it will return string containing the post type.
get_post_type( int|WP_Post|null $post = null )
$somePost; // post
$postType = get_post_type($somePost);
if ('page' === $postType) {
// page...
}
elseif ('post' === $postType {
// post...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With