Viewing 5 replies - 1 through 5 (of 5 total)
  • 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;
    ?>

    No, I don’t know the page ID – what now?

    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;

    And here’s an even shorter way to get it

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

    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*

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘get current page slug outside the loop’ is closed to new replies.