How to get post slug from post in WordPress?

后端 未结 10 2194
我在风中等你
我在风中等你 2020-12-25 09:32

I want to get \"abc_15_11_02_3\" from http://example.com/project_name/abc_15_11_02_3/. How can i do this?

相关标签:
10条回答
  • 2020-12-25 10:31

    Here is most advanced and updated version what cover many cases:

    if(!function_exists('the_slug')):
        function the_slug($post_id=false, $echo=true) {
            global $product, $page;
    
            if(is_numeric($post_id) && $post_id == intval($post_id)) {} else {
                if(!is_object($post_id)){}else if(property_exists($post_id, 'ID')){
                    $post_id = $post_id->ID;
                }
                if(empty($post_id) && property_exists($product, 'ID')) $post_id = $product->ID;
                if(empty($post_id)) $post_id =  get_the_ID();
    
                if(empty($post_id) && property_exists($page, 'ID')) $post_id =  $page->ID;
            }
    
            if(!empty($post_id))
                $slug = basename(get_permalink($post_id));
            else
                $slug = basename(get_permalink());
            do_action('before_slug', $slug);
            $slug = apply_filters('slug_filter', $slug);
            if( $echo ) echo $slug;
            do_action('after_slug', $slug);
            return $slug;
          }
    endif;
    

    This is collections from the best answers and few my updates.

    0 讨论(0)
  • 2020-12-25 10:33

    You can do this is in many ways like:

    1- You can use Wordpress global variable $post :

    <?php 
    global $post;
    $post_slug=$post->post_name;
    ?>
    

    2- Or you can get use:

    $slug = get_post_field( 'post_name', get_post() );
    

    3- Or get full url and then use the PHP function parse_url:

    $url      = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $url_path = parse_url( $url, PHP_URL_PATH );
    $slug = pathinfo( $url_path, PATHINFO_BASENAME );
    

    I hope above methods will help you.

    0 讨论(0)
  • 2020-12-25 10:34

    I came across this method and I use it to make div IDs the slug name inside the loop:

    <?php $slug = basename( get_permalink() ); echo $slug;?>
    
    0 讨论(0)
  • 2020-12-25 10:37

    Wordpress: Get post/page slug

    <?php 
    // Custom function to return the post slug
    function the_slug($echo=true){
      $slug = basename(get_permalink());
      do_action('before_slug', $slug);
      $slug = apply_filters('slug_filter', $slug);
      if( $echo ) echo $slug;
      do_action('after_slug', $slug);
      return $slug;
    }
    ?>
    <?php if (function_exists('the_slug')) { the_slug(); } ?>
    
    0 讨论(0)
提交回复
热议问题