Accessing $post global on a custom post type archive page

I have a custom post type called projects, and its archive is at /projects, on the archive page I get notices Notice: Trying to get property of non-object every time I try to access the $post i.e. $post-post_name. Is this intended behaviour? Should I just accept that and always check the availability of $post before using it?

if (!empty($post)) {
    // Do something with $post
}

Topic globals Wordpress

Category Web


You are trying to get array values, so you are getting errors. Try with WP_Query, like:

global $post;        
$projects = array(
    'post_type'   => 'projects',
    'orderby'     => 'date',
    'order'       => 'DESC',
    'post_status' => 'publish'
);
$projects1= new WP_Query( $projects );          
if ( $projects1->have_posts() ) : 
    while ( $projects1->have_posts() ) : 
        $projects1->the_post();
        echo $post->post_name;
    endwhile; 
endif; 

Put in the following line at the top of archive page :

global $post;

Thing is you need to access the global $post object before trying to use it.

About

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