I’m pretty new to WordPress and I was wondering if I could get a page id
with its slug
. Is it possible please let me know?
7 comments
Comments are closed.
I’m pretty new to WordPress and I was wondering if I could get a page id
with its slug
. Is it possible please let me know?
Comments are closed.
Use
get_page_by_path($page_path)
:This will return a regular post object.
Documentation:
https://developer.wordpress.org/reference/functions/get_page_by_path/
https://developer.wordpress.org/reference/functions/get_the_title/
I’ve been using this ..
Hope this will help someone.
It has been already asked and answered on this forum. I am pasting the same code from there.
Use this function to retrieve page id.
There is a function url_to_postid since WordPress v1.0.0 🙂 This task is easiest to achieve by using this function.
url_to_postid
When page is top-level page, only slug has to be given.
e.g.
url_to_postid('slug');
When the page is in lower hierarchy level (i.e. it has parent) you have to prepend parent slug divided by slash like so:
Edit: if this returns 0, you should flush permalinks (open the wordpress permalinks page in admin) – this is needed only once
I had problems with the chosen answer when trying to use the code several times in the same page. It kept on displaying all of my pages content at the same time in every instance. So I went back to thinking and came up with this simpler approach based on the WordPress Codex‘s documentation:
Maybe it can still be helpful to somebody out there ;D
A lot of answers here that seem overly complex, or don’t describe how to get the page ID specifically.
In the above description we’ve assigned the post object to $page – Once you have the post object you can get any of the info described here: https://codex.wordpress.org/Class_Reference/WP_Post
and a lot more
I hope this suggestion is helpful for someone.