How can I get the slug of a page or post?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Inside of your loop you can do:
global $post; echo $post->post_name;
Method 2
Another option is getting the slug by post ID:
$slug = get_post_field( 'post_name', $post_id );
Here is more info about get_post_field https://codex.wordpress.org/Function_Reference/get_post_field
Method 3
Outside the loop:
<?php $post_id = 11; $post = get_post($post_id); $slug = $post->post_name; ?>
Method 4
As per other answers slug is stored in post_name property. While it could be accessed directly I prefer the (underused) get_post_field() function for access post properties which have no proper API for them.
It requires post provided explicitly and doesn’t default to the current one.
If you want to get slug of the post outside the loop then use:
$post_id = 20; //specify post id here $post = get_post($post_id); $slug = $post->post_name;
If you want to get slug of the post from the loop then use:
global $post; echo $post->post_name;
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0