Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the post type within a Wordpress search loop

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;
like image 829
Quentin Veron Avatar asked Jul 14 '26 17:07

Quentin Veron


1 Answers

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...
 }
like image 199
revengeance Avatar answered Jul 16 '26 05:07

revengeance