Get Current Page Slug WordPress

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. Both methods below use the global $post variable. The first method shown below accesses a property within the $post variable while the second option uses the get_post_field method.

Option 1: Access post_name property of the Global Post Variable

Access the post_name property of the global post object.

global $post;
$post_slug = $post->post_name;

For your information, 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:

$post_slug = get_post_field( 'post_name' );

Sidenote: 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 and use get_post($post_id).

That’s all there is to it!

Leave a Reply

Your email address will not be published. Required fields are marked *