So if I search 'How to get current page slug', there are bunch of results that suggest to use following snippet.
global $post;
$post_slug = $post->post_name;
echo $post_slug;
But issue is, if I use it on pages where there is default loop, it will return slug of very first post from the default loop. What am I missing here? This answer seems globally accepted, am I doing something wrong?
So if I search 'How to get current page slug', there are bunch of results that suggest to use following snippet.
global $post;
$post_slug = $post->post_name;
echo $post_slug;
But issue is, if I use it on pages where there is default loop, it will return slug of very first post from the default loop. What am I missing here? This answer seems globally accepted, am I doing something wrong?
If you are inside the loop, you don't need to access global $post, you already have $post variable accessible in your local scope, and this variable holds the data from current loop iteration.
If you are outside the loop, then you need to access global $post first, and it will hold whatever data it was left with (the first post in the loop usually).
As I understand, you're trying to output the slug of the current post in your custom loop (not main). In this case, just use $post->post_name
;
wp_reset_postdata()
before yourglobal $post
( and/or$post->post_name
) – Howdy_McGee ♦ Commented Oct 10, 2017 at 18:42wp_reset_data();
before calling 'global $post' but it still behaves same. Please correct me, should it work on taxonomy template? or I am doing it wrong by trying to get slug on Taxonomy page. I know that I can use get_queried_object() and term from it. But I have complex scenario so maybe I will have to use combination of both. – Zorro Here Commented Oct 10, 2017 at 18:49