skip to Main Content

How can i get slug from url in wordpress. For example my url is https://ww.test.com/test-page/test-post/data-to-get how can i get data-to-get from url in wordpress. I tried following code

global $wp;
$current_url = home_url( add_query_arg( array(), $wp->request ) );

what is wrong here

2

Answers


  1. You can achieve your output using below methods.

    1. by using Global post variable.

       <?php 
         global $post; 
         $post_slug = $post->post_name; 
        ?>
      
    2. using PHP

       <?php
         global $wp;
         $current_url = $wp->request;
         echo substr($current_url , strrpos($current_url , '/') + 1);
        ?>
      

    Suppose URL: https://ww.test.com/test-page/test-post/data-to-get

    OUTPUT: data-to-get

    I have checked and it’s work for me.
    Let me know if this works for you.

    Login or Signup to reply.
  2. There is a built-in function for that in wordpress: url_to_postid.

    <?php
    global $wp;
    $current_url = $wp->request;
    $post_id = url_to_postid($current_url);
    $slug = get_post_field( 'post_name', $post_id );
    echo $slug;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search