0

I am using this code:

function the_alt_title($title= '') {
    $page = get_page_by_title($title);
    if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {
        $title = $p;
    }

    return $title;
}
add_filter('the_title', 'the_alt_title', 10, 1);

In debug.log i get

PHP Notice:  Trying to get property of non-object in /var/www/html/wp-content/themes/my-child/functions.php on this line:

 if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {

How could I fix this?

  • You need to do a check on $page to make sure it has the property of 'ID' – ngearing Nov 9 '16 at 23:13
  • Looking at the source code of get_page_by_title(), you'll notice it will return nothing if the page was not found, so go if ( !empty($page->ID) && $p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true) ) – Samuel Elh Nov 9 '16 at 23:51
2

$page = get_page_by_title($title) - this line is failing somewhere, so you should do a check on this to make sure it exists.

Like so:

function the_alt_title($title= '') {
    $page = get_page_by_title($title);
    if (!$page) {
        return $title;
    }

    if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {
        $title = $p;
    }

    return $title;
}
add_filter('the_title', 'the_alt_title', 10, 1);
0

Have to globalize page to access it.

    function the_alt_title($title= '') {
    global $page; //here
    $page = get_page_by_title($title);
    if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {
        $title = $p;
    }

    return $title;
}
add_filter('the_title', 'the_alt_title', 10, 1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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