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?
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.
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.
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.
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.
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;
?>
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With