• Hi, I am getting an undefined array key in 1 warning upon upgrading to PHP 8 with the following line, it doesn’t appear to impact anything but I would imagine in future versions of PHP it would. Has anyone come across this before using get_the_title?

    $parentMainVal = get_the_title($post->ancestors[1])
Viewing 4 replies - 1 through 4 (of 4 total)
  • Unfortunately, this one line says nothing at all. Where did you get it from? Where is it written? Is it from a plugin, theme, one of your own developments?

    However, the message is pretty clear. In the array $post->ancestors there is no entry with the index 1 which is queried there. How to solve this depends on where this line is located?

    Moderator bcworkz

    (@bcworkz)

    If we assume ancestors property comes from get_ancestors() (a huge assumption founded on no reliable information), then the item at index 1 would have been the grandparent page ID. It’s rash to assume any page would have a parent page (index 0) much less a grandparent page. It’s always a good idea to verify an array element exists before trying to use it. get_ancestors() will often return an empty array because the page has no ancestors.

    Like threadi said, the solution depends on the surrounding context and what should happen if there is no grandparent ancestor. But something like this might be included:
    if ( array_key_exists( 1, $post->ancestors )) :

    Thread Starter wyclef

    (@wyclef)

    Here is a little more context

    <?php  $parentVal = get_the_title($post->post_parent); ?>
    <?php  $parentMainVal = get_the_title($post->ancestors[1]) ?>
    <?php  if (is_page('home')) { ?>
    <body id="home">
    <?php  } else if (is_page('special') || ($parentVal == 'Special') || ($parentMainVal == 'Special')) { ?>
     <body id="special">
    <?php  } else if (is_page('misc') || ($parentVal == 'Miscellaneous') || ($parentMainVal == 'Miscellaneous')) { ?>
     <body id="misc">
    <?php  } else { ?>
    <body>
    <?php  }?>

    This is some old custom code I am rummaging through. Let me know if I need to do more digging.

    Unfortunately, this does not help much to recognise the origin. It is not clear where $post comes from. However, you can use @bcworkz’s tip to check whether the key exists before the output.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Undefined array key in 1 with get_the_title’ is closed to new replies.