Getting the current page name in WordPress is a handy skill for those looking to customize or develop their websites. Here are two ways to do it, broken down into simple steps.
This blog post will help you get current page name in WordPress. So if you are planning to create a WordPress plugin or want to fetch the current page then this simple code will be of great help.
Understanding What You’re Trying to Do
In WordPress, a page name refers to the slug or the URL part that identifies that page. For example, in the URL https://example.com/about-us
, “about-us” is the page name.
Method 1: Using Global $post
Variable
This method involves accessing the global $post
variable to retrieve the current page’s name or slug.
Step 1: Open the Relevant File
Access the file where you want to display or use the current page name, like functions.php
, single.php
, page.php
, or index.php
.
Step 2: Get the Current Page Name (Slug)
Use the following code:
global $post; $post_slug = $post->post_name;
Step 3: Display the Page Name
You can display the page name using:
echo 'Current page name is: ' . $post_slug;
Method 2: Using get_query_var
Function
This method can handle different scenarios, like when a static page is set as the front page.
Step 1: Get the Page Name from Query Variable
Use the following code to start:
$pagename = get_query_var('pagename'); if ( !$pagename && $id > 0 ) { $post = $absa_query->get_queried_object(); $pagename = $post->post_name; }
You can then use the $pagename
variable as needed.
Pro Tips
Check if You’re on a Page or Post: Use is_page()
or is_single()
functions to ensure you’re on a page or a post.
Use Proper Permissions: Always backup your site or work on a staging site first.
Consider Child Themes: If modifying a theme, consider creating a child theme to avoid overwriting your changes during updates.
Conclusion
Getting the current page name in WordPress can be accomplished through two methods: using the global $post variable or using the get_query_var function.
Both methods can be used for customizations or building special features on your site.
Always take care when making changes to theme files, and consider using a child theme if modifying a theme you didn’t create yourself.
Trouble Shooting? Get Help From Us
This code works fine if done properly. But still, if you are unable to get current page name in WordPress then Request a Quote. Our WordPress support staff will be in touch with you within minutes and assist you.
Apart from offering WordPress services and support, we also accept HTML to WordPress template conversion requests.