How to retrieve the slug of the current page in WordPress?

In WordPress, you can retrieve the slug of the current page using the get_post_field function. The get_post_field function takes two parameters: the post ID and the field you want to retrieve. To get the slug of the current page, you need to pass 'post_name' as the second parameter, like this:

bash
$slug = get_post_field( 'post_name', get_post() );

The get_post function retrieves the current post object, which can then be passed as the first parameter to get_post_field to retrieve the post_name field, which is the slug of the current page.

It’s important to note that this method only works for single posts, pages, and custom post types. If you’re trying to retrieve the slug for an archive page (such as a category archive or tag archive), you’ll need to use a different approach.

For example, if you’re trying to retrieve the slug for a category archive, you can use the get_queried_object function, like this:

bash
$category = get_queried_object();
$category_slug = $category->slug;

Similarly, if you’re trying to retrieve the slug for a tag archive, you can use the following code:

bash
$tag = get_queried_object();
$tag_slug = $tag->slug;

These are some of the most common methods to retrieve the slug of the current page in WordPress. By using these techniques, you can easily retrieve the slug for any type of page on your WordPress site, and use it for various purposes such as creating custom URLs, adding CSS classes to specific pages, and more.