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?

2
  • You need to do a check on $page to make sure it has the property of 'ID'
    – ngearing
    Commented Nov 9, 2016 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) )
    – Ismail
    Commented Nov 9, 2016 at 23:51

2 Answers 2

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
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 and acknowledge you have read our privacy policy.

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