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?

  • Well, on Pages in the default loop it should only contain one post, the Page. Maybe you have a query somewhere messing things up, try using wp_reset_postdata() before your global $post ( and/or $post->post_name)
    – Howdy_McGee
    Oct 10, 2017 at 18:42
  • I've had this same problem. @Howdy_McGee is right, you likely have a different query running in a function or somewhere else that you didn't use wp_resent_postdata()
    – rudtek
    Oct 10, 2017 at 18:45
  • I tried using wp_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
    Oct 10, 2017 at 18:49
  • Taxonomy templates show groups of posts. There are no "Pages" attached to a taxonomy or even a term. Are you trying to get the term or are you trying to get a post attached to the term?
    – Howdy_McGee
    Oct 10, 2017 at 20:13
  • I will try to rephrase my problem, I have some common links on multiple pages. Few of it are links to categories and few of it are for posts. I want to highlight those if you are viewing that category or that post. But problem is, If I use any methods to get permalink/slug of current post/taxonomy being viewed, it returns values for first post from loop while viewing taxonomy instead of that taxonomy itself. How can I do that?
    – Zorro Here
    Oct 11, 2017 at 6:32

1 Answer 1

  1. 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.

  2. 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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.