4

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
}
  • 2
    You should only use $post within the loop. – TheDeadMedic Oct 14 '15 at 9:13
  • What alternatives there are outside the loop? – any_h Oct 14 '15 at 9:20
  • 2
    You can use if ( have_posts() ) $post = $wp_query->posts[0]; – TheDeadMedic Oct 14 '15 at 9:21
  • 1
    It doesn't make a lot of sense to make use of $post outside the loop in a post archive, mainly because it yields the problem of "which post?" There are other functions that can provide more useful information though, such as the current post type and its labels, or the current category/tag/term – Tom J Nowell Nov 13 '15 at 9:22
  • Is this question still current? What is it that you want to achieve on this template? – Andy Macaulay-Brook Aug 4 '16 at 18:47
0

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.

  • It doesn't help in this case. – any_h Oct 15 '15 at 14:29
  • Than only thing I can think of, is that you are trying to access it on a page where it was not set. However still you can avoid error message by testing if object exists by using : is_object() – Fiaz Husyn Oct 26 '15 at 19:40
0

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; 

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.