How to Get Current Page Slug in WordPress

get current page slug in wordpress post slug featured image

Getting a page or post slug in WordPress is very useful especially when you are trying to display it on your page. It is also useful for SEO purposes.

A slug is a part of a post or page URL. It contains the post title and the spaces are replaced with dashes “-“. A post slug can be seen and is a part of the post permalink if you set the permalink setting to post name.

There are a few ways on how to retrieve or get the current page slug in WordPress.

Method 1: Get Current Page Slug Using POST_NAME Property of the Global Post Variable

Most of the time, posts and page slug can be called using a WordPress global object’s post_name.

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

Method 2: Using GET_POST_NAME function

You could also use the get_post_field function to get the current page or post slug.

If you are inside the loop, you can copy the following code below:

$current_page_slug = get_post_field( 'post_name' );

get current page slug in wordpress post slug example functions php

get current page slug in wordpress post slug functions php example

If you are outside a loop, usually there is a need to call a second argument which is the post ID. You’ll get errors you don’t do since it is the variables needed by the get_post_field method.

$current_page_slug = get_post_field( 'post_name' , $post_id );

Leave a Comment

Scroll to Top