How to obtain the current page Slug in WordPress (PHP example)
1 min read

How to obtain the current page Slug in WordPress (PHP example)

WordPress slug is used to access pages and articles on WordPress. For example, if I have an article titled “Hello”, its label would be “/hello”. WordPress does this to assist search engine optimization through human readable URLs. When building a website using WordPress, this concept is very important because you may want to use the correct slug links to the page.

Please note that this guide assumes that you have some understanding of PHP and are currently developing custom WordPress features using themes or plugins.

In this short article, we will introduce several methods of using PHP to obtain page slugs in WordPress.

Using get_post_field to obtain page labels in WordPress

In the WordPress backend, slug is actually referred to as “postname”. This variable can be accessed using the get_post_field() function. This is the best way to obtain slugs in WordPress, as it can be used in the main query or loop to obtain multiple WordPress slugs.

// 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 above example, I demonstrated how to retrieve the title of the current page in WordPress. In addition, I have added an example that allows you to obtain tags for any WordPress page through the article ID.

Using global $post in WordPress to retrieve the current page’s Slug

The global object named $post in WordPress contains the current article object of the current article. This method is very useful when you want to get the title of the current page or article.

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

Now you have some understanding of WordPress!

I hope this guide is helpful to you. If you have any questions about WordPress development, please let me know in the comments below.