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

2.8k Views Asked by At

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?

2

There are 2 best solutions below

2
Vyacheslav On BEST ANSWER

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];
0
miepsik On

I think $page is an integer not an object so $page->ID return 0. Just remove $page->ID and use only $page % 3