There are several ways to get the current page’s or post’s slug in WordPress. Most simply, a post’s or page’s slug can be retrieved by accessing the global post object’s post_name property. The first method shown below accesses that post_name property within the $post variable while the second option below uses the get_post_field method.
Both methods below use the global $post variable, but if you only have access to the current page’s post id, the second option provides an alternative method that uses a post_id to get the slug.
Option 1: Access post_name property of the Global Post Variable
Access the post_name property of the global post object.
global $post;
$page_slug = $post->post_name;
For your information, in WordPress, pages are a post type, which is why the $post variable gives you information about the page. Also, the global post object holds data associated with the current page or post that is being accessed. This global variable is available inside WordPress’ loop. The WordPress loop is “PHP code used by WordPress to display posts” per https://codex.wordpress.org/The_Loop.
Option 2: Use the get_post_field method
You could also use the get_post_field function to get the current page or post slug. IF you are inside the loop, this looks like the following code:
$page_slug = get_post_field( 'post_name' );
If you are outside of the post loop, you will need a second argument for the get_post_field function. For that second argument, you could use a $post_id value. See code below as an example:
$page_slug = get_post_field( 'post_name', $post_id );
That’s all there is to it!