Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get post slug from post in WordPress?

Tags:

wordpress

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?

like image 202
user1990 Avatar asked Nov 21 '15 10:11

user1990


People also ask

How do I get a current post slug?

You could also use the get_post_field function to get the current page or post slug. IF you are inside the loop, this looks like the following code: $page_slug = get_post_field( 'post_name' ); If you are outside of the post loop, you will need a second argument for the get_post_field function.

How do I find the slugs of a WordPress page?

If you'd like to find the slug for a category or tag, visit Posts → Categories or Posts → Tags in the Dashboard. Once you've loaded the Category or Tag page, you'll see a listing on the right of all your current items. The Slug column will display the slug for each category.

How do I find my slug ID?

The WordPress function to get post slug by id is get_post_field which returns a string. get_post_field should pass at least two parameters to retrieve the slug value. Although, the function can receive three arguments.

What is a post slug?

The post slug is the user friendly and URL valid name of a post. Most common usage of this feature is to create a permalink for each post. WordPress automatically generates post slugs from a post's title. However, it is not used in the URL until custom permalinks are enabled for use ” %postname%” in the URL structure.


3 Answers

You can get that using the following methods:

<?php $post_slug = get_post_field( 'post_name', get_post() ); ?>

Or You can use this easy code:

<?php
    global $post;
    $post_slug = $post->post_name;
?>
like image 80
Keyur Patel Avatar answered Oct 21 '22 07:10

Keyur Patel


If you want to get slug of the post from the loop then use:

global $post;
echo $post->post_name;

If you want to get slug of the post outside the loop then use:

$post_id = 45; //specify post id here
$post = get_post($post_id); 
$slug = $post->post_name;
like image 26
Domain Avatar answered Oct 21 '22 07:10

Domain


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.

like image 22
Yatin Khullar Avatar answered Oct 21 '22 07:10

Yatin Khullar