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:

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

What gives? Does get_page_by_title not accept variables?

Related posts

2 comments

  1. 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;
    }
    
  2. Retrieve post/page/custom-post-type id it works fine

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

    Note:enable WP_DEBUG in wp-config.php to see all errors and warnings and use var_dump to check values in variables.

    For more info: read get_page_by_title() not returning anything

Comments are closed.