get_page_by_title not working when used with a variable

My page title is This is my title, if I try and retrieve the ID from the title like this then it does not work:

$mytitle="This is my title";
$mytitle2 = get_page_by_title( $mytitle, OBJECT, 'mycustompost' );
print_r($mytitle2);

But if I do this it does work:

$mytitle2 = get_page_by_title( 'This is my title', OBJECT, 'mycustompost' );
print_r($mytitle2);

What gives? Does get_page_by_title not accept variables?

2 Answers
2

Man this was an annoying problem for me as well because I a function passing the variable and when tested it showed a value (with special characters, like “&”. If I reset the value statically it worked but otherwise same issue. I ran html_entity_decode() on the variable and it now works perfectly so thought I would pass on in case it helps someone. Here was my function:

public function get_id_by_code($coupon){
    $test = get_page_by_title( html_entity_decode( $coupon ), OBJECT, 'coupon' );
    return $test->ID;
}

Leave a Comment