Let's say I have a page with the name sample-page.

I can do this:


To get that page.

Now, let's say I want to get a post where the URL to that post is /post/8.

If I do

get_page_by_path('post/8'); // with or without leading slash

I get back null.

How do I retrieve the page/post for any given URL in WP?

Edit: here's a screenshot that might add some clarity to my issue

enter image description here

Given the frontend permalink URL is /post/33, how do I take that string and do the opposite? How do I take /post/33 and get the post from that?


You can use url_to_postid() to get the post ID with the relative page url.

$url = '/page-parent/page/';
$post_id = url_to_postid( $url );


  • This seems to return 0 for me. url_to_postid('post/8') returns 0. Jun 5 '19 at 14:15
  • did you try with a front slash?
    – rudtek
    Jun 5 '19 at 14:23
  • Yep it acts the same with or without a leading slash. Jun 5 '19 at 14:27
  • @JoshuaSoileau @MarkMarzeotti Function url_to_postid() will not work with relative URL. One of the first things that the function checks is whether the URL belongs to the domain of the site.
    – nmr
    Jun 5 '19 at 15:02
  • Even giving a full URL doesn't seem to work: home_url('/post/33/') returns "https://my_site.com/post/33/", but get_page_by_path( home_url('/post/33/') ) and url_to_postid( home_url('/post/33/') ) both return null Jun 5 '19 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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