5

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
}
5
  • 3
    You should only use $post within the loop. Commented Oct 14, 2015 at 9:13
  • What alternatives there are outside the loop?
    – any_h
    Commented Oct 14, 2015 at 9:20
  • 2
    You can use if ( have_posts() ) $post = $wp_query->posts[0]; Commented Oct 14, 2015 at 9:21
  • 2
    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
    Commented Nov 13, 2015 at 9:22
  • Is this question still current? What is it that you want to achieve on this template? Commented Aug 4, 2016 at 18:47

3 Answers 3

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.

2
  • It doesn't help in this case.
    – any_h
    Commented Oct 15, 2015 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
    Commented Oct 26, 2015 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; 
0

I would probably just check if the post exists first to prevent errors: using post_exists() WP codex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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