admin管理员组

文章数量:1278793

get_page_by_title works fine on plain text title. but when it comes to smart quotes and symbols like # it doesn't work. It fails to find post with the given title.

For Example:-

get_page_by_title('The #1 Reason to Buy Right Now – THE MONEY!!', OBJECT, 'post');

returns NULL.

But there exists a post with this title. If there is a better way to do so, then that would be great.

get_page_by_title works fine on plain text title. but when it comes to smart quotes and symbols like # it doesn't work. It fails to find post with the given title.

For Example:-

get_page_by_title('The #1 Reason to Buy Right Now – THE MONEY!!', OBJECT, 'post');

returns NULL.

But there exists a post with this title. If there is a better way to do so, then that would be great.

Share Improve this question asked Jun 5, 2015 at 20:50 Omar TariqOmar Tariq 6762 gold badges8 silver badges26 bronze badges 1
  • 1 So this doesn't work on a vanilla install? – birgire Commented Jun 5, 2015 at 22:02
Add a comment  | 

4 Answers 4

Reset to default 1

You may need to html entity decode that title. Similar to the issue found here. Try this:

get_page_by_title(
    html_entity_decode('The #1 Reason to Buy Right Now – THE MONEY!!'), 
    OBJECT, 
    'post',
));

The '#' character in title is not a problem. Second parameter of the function is a string. Change OBJECT to 'OBJECT'. That's all.

Anyone stumbling on this here is the solution:

get_page_by_title(esc_html('The #1 Reason to Buy Right Now – THE MONEY!!'), OBJECT, 'post');

Escaping the value encodes the special characters to match the title.

In case someone needs it.

$post = get_page_by_title(wp_unslash(sanitize_post_field( 'post_title', 'This is my Title', 0, 'db' ) ), OBJECT, 'post')

本文标签: postsgetpagebytitle() not working if special characters are present