There are multiple ways to get slug from url in wordpress. In this article we will show you the code examples of some of these most useful ways.
Code Example
1. Using get_post_field()
function
<?php $post_slug = get_post_field( 'post_name', get_post() ); ?>
2. Using global $post
variable
<?php global $post; $post_slug = $post->post_name; ?>
3. Using post id
$post_id = 45; //specify post id here $post = get_post($post_id); $slug = $post->post_name;
4. Using parse_url()
method
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $url_path = parse_url( $url, PHP_URL_PATH ); $slug = pathinfo( $url_path, PATHINFO_BASENAME );
5. Using get_permalink()
method
For any post using post_id –
$postId = get_the_ID(); $slug = basename(get_permalink($postId));
For current post –
$slug = basename(get_permalink());