wordpress get page slug is a keyword that a lot of you search for! Congratulations! Wpexpelor is the site that is going to teach you how to get a wordpress page slug! Depending on your goal, getting a wordpress page slug can do you good in many cases! Page slug is usually used in defining conditions, detecting the page and so many important things, too! As a simple example of page slug usage, I can mention WooCommerce. WooCommerce plugin uses cart slug as the shopping cart and shop slug as the store itself!
Note: I’m sure you know the slug is the editable part of the URL page in your wordpress website.
wordpress get page slug: easy trick!
The question is how to get the page slug in wordpress? To answer this, we should first find out if we are going to get the page or post slug. To do so, follow the steps:
Open file manager (using FTP or your website control panel)
Open “wp-content” and then “themes” folder.
Look for these files depending on your goal:
- “single.php” is for getting post slug in wordpress
- “page.php” is for getting page slug in WordPress
Both files have the same structure. Now open the one that you need. Logically, we can only get page slug if we are in “content loop”. WordPress content loop has a structure like this:
<?php
// Start the loop.
while ( have_posts() ) :
// content...
// End the loop.
endwhile;
?>
And in this structure our content is showing up. By content, I mean any type of content as text, pictures, titles, and….. I’m going to teach you how to show a page slug at the end of a content loop. So, I open the “single.php” file to edit and add this part of the code:
global $post;
$slug = $post->post_name;
echo "slug is: ". $slug;
Why does this part of the code work, and what is the logical proof?!
As you can see, I’ve recalled a global variable named “post”. Pay attention that “post” is not defined by me! It has already been defined in wordpress structure. In the next line, I’ve defined slug (I could have named it anything else!). Page slug would be saved in this variable. Eventually, at the end of the page, we can see the page slug (with the command “echo”). Here is the result:
I hope this article of wpexpelor will be useful your you. I would be really happy to hear from you! Best.