Search code examples
phpwordpresswordpress-themingcustom-wordpress-pagese-notices

How to fix PHP Notice: Trying to get property of non-object in Wordpress template?


I'm working on a Wordpress template content-article.php

Here are the segment of my code:

$article_field[];
$article_field[] = 'test1';
$article_field[] = 'test2';
$article_field[] = 'test3';

echo $article_field[($page->ID + $page) % 3];

The PHP Notice: Trying to get property of non-object, is taking place at the line of echo

Even there's a warning, the script still execute fine and giving me correct result.

I'm rotating the $article_field[] element display based on pagination variable $page, where array index is calculated by current page id + page number % 3

How do I fix this PHP Notice?


Solution

  • I may be wrong, but if I've understood you right you want to get current post id? If yes,

    $post_id = get_the_id()
    

    and your output will be something like this:

    echo $article_field[($post_id + $page) % 3];