3

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?

4
  • Tried it with a page, it works. I suggest you replace print_r by var_dump so that you'll get NULL result if no post is found.
    – RRikesh
    May 23, 2013 at 10:55
  • I've just tried with var_dump and I am getting NULL. So does that look like its not finding the post? May 23, 2013 at 11:07
  • 1
    This worked for me: $y = 'Sample Page'; $x = get_page_by_title( $y , OBJECT, 'page' ); var_dump( $x ); You should double check your code (and post type)
    – RRikesh
    May 23, 2013 at 11:10
  • On testing I can see that it works fine unless the title has a dash, then it fails. Could it be something to do with special characters? May 23, 2013 at 11:13

2 Answers 2

4

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
  • I stumbled on something similar. My CPT entry had a dash in it (entered as a hyphen-minus character), but WP displays it as an em-dash, so when I copied the rendered title into get_page_by_title(), it naturally didn't match what was in the database. It didn't help that my font in Sublime Text makes it very tricky to distinguish between the two as well.
    – GaryJ
    Mar 16, 2015 at 8:44
  • This is nuts. The titles for my CPT don't even have special characters in them (alphanumeric with no spaces) yet get_page_by_title() still fails without html_entity_decode(). Thanks for the fix!
    – Andy P
    Oct 23 at 16:32
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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