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

This code is used after <head> and before <body> and is supposed to get current page's slug. It works great, however it will get the slug of first blog post when on "general" blog page.

Example:

  • Blog url: www.my-site.com/blog/ -> slug in admin area is set to blog
  • Blog post url: www.my-site.com/post-1/ -> slug in admin area is set to post-1

Code echoes post-1 for both. Any ideas?

3 Answers 3

0

This code is used after <head> and before <body> and is supposed to get current page's slug. It works great, however it will get the slug of first blog post when on "general" blog page.

$post is going to be set to the first post in the Loop when the page loads. On "page" pages with only one post in the Loop that is going to be the page data you expect. On archive pages it will be the first post in the set of posts on the page. This is what appears to be happening. You can't trust $post explicitly like that-- that is, without understanding exactly when it is set to what. (Most loops, even secondary ones, will alter this variable as well)

To get the page data itself you need get_queried_object() but be careful with that too as it will be different on various types of pages-- sometimes a post object, sometimes a user object, sometimes null.

1

get_queried_object Retrieve the currently-queried object.

 $queried_object = get_queried_object();

 var_dump( $queried_object ); 

  • if you're on a single post, it will return the post object
  • if you're on a page, it will return the page object
  • if you're on an archive page, it will return the post type object
  • if you're on a category archive, it will return the category object
  • if you're on an author archive, it will return the author object
  • etc.
0
global $wp_query;
$post_id = $wp_query->post->ID

$post = get_post( $post_id );
$slug = $post->post_name;

echo $slug;

This should be the best solution in case you have to ask for it from a secondary loop, and if you getting the wrong slug with only the global $post variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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