How to include support for all page types, calendar urls, archive, etc

I'm writing a plugin and I get this error when viewing calendar urls for example the calendar archive list on a wordpress site. I do not get the error on posts or pages, only get error when viewing a set of posts via calendar/archive/calendar url (example of what I mean by calendar url. thewebsite.com/2021/08 -not an actual link-.). (Also, the error shows on the search page.) I assume the error means I am not including compatibility for other types of pages, like archives, searches, urls showing sets by date, etc. I'm new to programming. Please give me any comments if you have any thoughts after seeing this portion of code. The error message is Notice: Trying to get property 'post_type' of non-object The code I am trying to write better:

$wp_the_query   = $GLOBALS['wp_the_query'];
$queried_object = $wp_the_query-get_queried_object();
$post_object    = sanitize_post( $queried_object );
$post_type      = $post_object-post_type;
$post_id        = $post_object-ID;

UPDATE: Below is the way I solved the problem, changed the code to this: (please comment if you see problems.)

$wp_the_query   = $GLOBALS['wp_the_query'];
$queried_object = $wp_the_query-get_queried_object();

if ( is_singular() ) :
 $post_object    = sanitize_post( $queried_object );
 $post_type      = $post_object-post_type;
 $post_id        = $post_object-ID;
endif;

Topic calendar php urls Wordpress

Category Web


You need to add a check if the view that you are currently on is a single-view page or an archive ( or any other taxonomy page ). If you are on an archive page, the get_queried_object() will not return a Post object, therefore the error

The check you need to add can be the following:

if ( ! is_archive() ) {
    $wp_the_query   = $GLOBALS['wp_the_query'];
    $queried_object = $wp_the_query->get_queried_object();
    $post_object    = sanitize_post( $queried_object );
    $post_type      = $post_object->post_type;
    $post_id        = $post_object->ID;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.