WordPress.org

Ready to get started?Download WordPress

Forums

get current page slug outside the loop (6 posts)

  1. Argonisius
    Member
    Posted 2 years ago #

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

  2. dkotter
    Member
    Posted 2 years ago #

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

    <?php
    $post_id = 11;
    $post = get_post($post_id);
    $slug = $post->post_name;
    ?>
  3. Rulatir
    Member
    Posted 2 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
    Member
    Posted 2 years ago #

    And here's an even shorter way to get it

    global $post;
    $slug = get_post( $post )->post_name;
  6. Good in Today
    Member
    Posted 1 year 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

Tags