0

I am using this code in a page template to determine the custom post type and display a different template for each custom post type.

if ( $query->have_posts() )
 {
    ?>
 <ul id="floros">
    <?php
    while ($query->have_posts())
    {
        $query->the_post();

        ?>

<?php
    $curtype = get_post_type( $post->ID );
    switch ($curtype) {
        case "events":
        ?>

        <?php
        break;
        case "brands":
        ?>
..etc

However i have an issue with this line: $curtype = get_post_type( $post->ID );

Trying to get property 'ID' of non-object in search-filter/results.php on line 37
PHP Notice:  Undefined variable: post in search-filter/results.php on line 37

The page shows results as expected, however the debug log is filled with duplicated lines of the above. I suppose I need to somehow check only for the type of the first object to avoid this error?

2

The error says it all. You are trying to get property ID of non-object. That means that the $post var is not an object.

You can get current post ID within a WordPress loop using get_the_ID(), but actually you don't need it in this case (see explanation below).

if ( $query->have_posts() ) {

    while ( $query->have_posts() ) {

        $query->the_post();

        $current_post_type = get_post_type( get_the_ID() );

        // Use $query->post if you want to get
        // current post object in full
        // ex: $query->post->ID

    }

    // Do not forget to reset post data after a custom wp_query loop
    // to restore global $post to main wp_query data
    wp_reset_postdata();

}

PD: Actually, $query->the_post() sets global $post to current post within the loop, and get_post_type() checks global $post if it doesn't receive a different post data or ID, that is why your code works as expected despite the error.

| improve this answer | |
  • 1
    great thanks for the explanation ! – JoaMika Apr 9 at 18:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.