Get Current Page Slug in WordPress (PHP Examples)

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.

<?php
// Get the current post or page's slug
$slug = get_post_field( 'post_name', get_post() );
echo $slug;
// Get slug for a post or page by ID
$post_id = 1;
echo get_post_field( 'post_name', $post_id );

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.

<?php
global $post;
$slug = $post->post_name;

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.

Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 10 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way.

One Response

Leave a Reply

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

WordPress Tips Monthly

Get the latest from SmartWP to your inbox.