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?
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?
Share Improve this question edited Apr 9, 2020 at 18:05 cybmeta 20.6k5 gold badges47 silver badges57 bronze badges asked Apr 9, 2020 at 17:32 JoaMikaJoaMika 6986 gold badges27 silver badges58 bronze badges1 Answer
Reset to default 5The 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.