It's difficult to get a hold of your code with what you've provided. As I don't which line from your snippet gives the error. However, there are a couple of places where this can happen.
$nextID = $query->posts[$key + 1]->ID;
$prevID = $query->posts[$key - 1]->ID;
You have a query, with an array of posts $query->posts
, however, your doing a calculation based off the $key
variable. For example. If there are 4 items in your array. The last $key
variable will contain 3. But as your adding +1 it can not find that array item.
Try changing your code to something like:
<?php
declare(strict_types=1);
foreach ($query->posts as $key => $value) {
$nextID = null;
$prevID = null;
if ($value->ID == $post->ID) {
$hasNextId = isset($query->posts[$key + 1]);
$hasPrevId = isset($query->posts[$key + 1]);
$nextID = $hasNextId ? $query->posts[$key + 1]->ID : null;
$prevID = $hasPrevId ? $query->posts[$key - 1]->ID : null;
break;
}
}
I have added to boolean variables, to check if the post as a previous ID (for the first array key). And if the post as a next ID (for the last array key).
If they don't have a next or prev ID, the value for $nextID
and/or $prevID
will be null
. This will mitigate the error, however, it could break code further down the line. Please make sure to add appropriate checks for example:
old code:
echo "next is " . $nextID;
new code:
if ($nextID !=== null) {
echo "next is " . $nextID;
}