The WordPress slug is a part of the URL that’s used to access specific pages or posts in WordPress. For instance, if there’s a post named “Hello World” its slug would be “/hello-world.” WordPress uses slugs to create URLs that are easy to read and good for SEO. When you’re working with WordPress, it’s important to understand slugs because you might want to link to pages using their correct slugs.
Keep in mind that this guide assumes you have some knowledge of PHP and are working on custom WordPress features using a theme or a plugin.
In this short article, we’ll explore a few ways to retrieve the page slug in WordPress using PHP.
Get Page Slug in WordPress Using get_post_field
When you’re working on the inside of WordPress, the thing that’s like a slug is actually named “post_name.” To get this part, you can use a special function called get_post_field(). This is the best way to get a slug in WordPress because it works well in the main part of WordPress that handles lots of things. You can use it to get many WordPress slugs at once.
<?php // Get the current post or page's slug $slug = get_post_field( 'post_name', get_post() ); echo $slug; // Get slug for a post or page by ID $post_id = 1; echo get_post_field( 'post_name', $post_id );
In the examples I’ve provided above, I demonstrate how to find the slug of the current page in WordPress. Moreover, I’ve included an example that lets you obtain the slug of any WordPress page using its post ID.
Get Current Page Slug in WordPress Using Global $post
The special object in WordPress known as “$post” holds information about the current post. This can be handy when you want to find the slug of the current page or post.
<?php global $post; $slug = $post->post_name;
Now you’ve gained some knowledge about WordPress! I hope this guide was useful. If you have any questions about WordPress development, feel free to ask in the comments below.
Related Articles
Leave a Reply