The WordPress slug is what is used to access pages and posts on WordPress. For example if I had a post titled “Hello” its slug would be “/hello”. WordPress does this to help with SEO by having human-readable URLs. This concept is important when building with WordPress since you might want to link to pages using their correct slug.
Note that this guide assumes you know some PHP and are developing custom WordPress functionality using a theme or plugin.
In this quick post we’ll be going over a few ways to get page slug in WordPress using PHP.
Get Page Slug in WordPress Using get_post_field
While on the WordPress backend the slug is actually called “post_name”. This variable can be accessed using the get_post_field() function. This is the best way to get a slug in WordPress since it can be used in the main query or loop to grab multiple WordPress slugs.
In the examples above I show how to get the current page slug in WordPress. Additionally I’ve added an example that allows you to get any WordPress page slug by their post ID.
Get Current Page Slug in WordPress Using Global $post
The global object in WordPress with the name $post carries the current post object for the current post. This is useful when you want to get the current page or post’s slug.
You now know a little more about WordPress!
I hope this guide was helpful, if you have questions about WordPress development let me know in the comments below.