get current page slug outside the loop (6 posts)

  1. Argonisius
    Posted 4 years ago #

    is there a way to get current page's slug outside the loop?

  2. Darin Kotter
    Posted 4 years ago #

    If you know the page ID, you can do something like this:

    $post_id = 11;
    $post = get_post($post_id);
    $slug = $post->post_name;
  3. Rulatir
    Posted 4 years ago #

    No, I don't know the page ID - what now?

  4. You can the post id of the current page outside the loop using the technique below.

    global $wp_query;
    $post_id = $wp_query->post->ID
    $post = get_post( $post_id );
    $slug = $post->post_name;
  5. Frankie Jarrett
    Posted 3 years ago #

    And here's an even shorter way to get it

    global $post;
    $slug = get_post( $post )->post_name;
  6. Good in Today
    Posted 3 years ago #

    I'm trying to use this in a template file that auto-generates a post when someone uploads an image. The post slug is to be utilized as a link to the image post itself, so that when the image is clicked on via the homepage, it takes you to the image post as you would expect. When I use the code provided here nothing is returned. Any ideas as to why? I tried what Frankie said and it came up blank, but I'm outside The Loop and I believe that global $post requires you be inside The Loop. Then I tried Chris's code and it STILL comes up blank. *sigh*

Topic Closed

This topic has been closed to new replies.

About this Topic