Extract slug from permalink

I want to extract the slug from post permalink when pretty permalinks is enabled.
If the permalink is:
http://sitename.com/category/best-post

Grabbing only “best-post”.
(My end goal is to query posts by posts urls)

Read More

Any help will be appreciate!

Related posts

2 comments

  1. Split the string by the slashes and take the last bit:

    $url = "http://sitename.com/category/best-post";
    $parts = explode("/", $url);
    echo $parts[count($parts) - 1]; // best-post
    
  2. You can simply use the global $post object like below:
    within the loop you can use,
    global $post;
    $post_slug=$post->post_name;

    or

    global $post;
    $slug = get_post( $post )->post_name;
    

    and outside the loop you can do it like this,
    global $wp_query;
    $post_id = $wp_query->post->ID

    $post = get_post( $post_id );
    $slug = $post->post_name;
    

    Not tested 100% but it should work for you

Comments are closed.