Get Current Page Slug in WordPress
When working with WordPress, developers often need to retrieve information about the current page being viewed. One crucial piece of information is the page slug. The slug is a part of the URL that identifies a specific page on a WordPress website. It is essential for tasks such as creating dynamic content, generating custom templates, or building navigation menus.
In this article, we will explore different methods to retrieve the current page slug in WordPress.
1. The WordPress global variable: $post
The $post global variable in WordPress holds information about the current post or page being displayed. By accessing the $post->post_name
property, we can obtain the slug of the current page. Here’s an example of how to retrieve the page slug using this method:
$current_page_slug = $post->post_name;
2. The WordPress function: get_post_field()
WordPress provides a handy function called get_post_field() that allows us to retrieve specific fields of a post or page. By passing ‘post_name’ as the $field
parameter and the ID of the current page as the $post parameter, we can obtain the page slug. Here’s an example:
$current_page_slug = get_post_field('post_name', get_the_ID());
3. The WordPress function: get_query_var()
If you are working with custom queries or modifying the main query, you can use the get_query_var() function to retrieve the page slug. WordPress automatically parses the URL and sets query variables based on the URL structure. To fetch the current page slug, you can use the ‘name’ query variable. Here’s an example:
$current_page_slug = get_query_var('name');
4. The WordPress function: sanitize_title()
Another method to obtain the page slug is by using the sanitize_title() function. This function takes a string and generates a URL-friendly version of it. By passing the post title or the page title as an argument, we can get the sanitized slug. Here’s an example:
$current_page_slug = sanitize_title(get_the_title());
Conclusion
Retrieving the current page slug in WordPress is an essential task for many developers. Whether you need it for generating dynamic content, building navigation menus, or creating custom templates, the methods mentioned in this article will help you obtain the page slug effortlessly. Depending on your specific requirements and the context of your code, choose the method that best suits your needs. By leveraging the power of these techniques, you can enhance the functionality and customization of your WordPress website.