Mar 5, 2012

Wordpress: Get page slug

So what if you need the page slug when programming on Wordpress? It doesn't have a function like "the_slug()". But no problem! You can put this code inside your "functions.php", located in your theme folder, and use it in your theme code!

function get_the_slug() {
    global $post;
    if ( is_single() || is_page() ) {
       
        return $post->post_name;        
    }else{
        return "";   
                  }   
}
You can use this function to generate a custom code for your page, according to the page you are in, like:

<?php
    if (get_the_slug()=="Contact"){
        echo "<span>Welcome to Contact section!</span>"
    }
?>
 BTW I got the code from the Wordpress codex (link here) , thanks to sligowaths for the code! I just tought that it would be nice to make it a bit more visible and show it's use.

Have fun!

No comments:

Post a Comment