Getting the post slug from a post in WordPress can be done in a few simple steps. The post slug is the user-friendly and URL-valid name of a post. Most often, post slugs are generated from the title of a post, replacing spaces with hyphens and removing any special characters.
Here’s how you can retrieve it:
Identify the Template File: First, you need to decide where you want to display or use the post slug. This could be in your theme’s single post template (
single.php), within the loop in your main blog page template (
index.php), or somewhere else depending on your needs.
Insert the Post Slug Function: Once you’ve opened the correct template file, find the place within the WordPress Loop where you want to display or use the post slug. Then, insert the following line of code:
<?php $post_slug = $post->post_name; ?>
This line of code creates a variable
$post_slug and assigns it the value of the current post’s slug. You can then echo this variable where you want it displayed like so:
<?php echo 'Post Slug: ' . $post_slug; ?>
Save and Upload Your Changes: After you’ve added these lines, save your changes to the file. If you’re editing the file offline, don’t forget to upload it back to your server using an FTP client.
Check Your Site: Now, you can visit your site and navigate to a post where you’ve added the code. The post slug should be visible at the location you inserted the echo line.
Remember to always back up your files before making any changes. If you are uncomfortable editing your theme files, you may want to ask for assistance from a developer.