Im pretty new to wordpress and I was wondering if I could get a page id with it's slug. Is it possible please let me know.

up vote 32 down vote accepted

Use get_page_by_path($page_path):

$page = get_page_by_path( 'about' );
echo get_the_title( $page );

This will return a regular post object.

  • What if it's a child page's id I want? – freaky Jun 13 '13 at 11:10
  • 1
    @freaky The function takes just the page slug, not the parent slug. Since slugs are unique, you will always get just one page. – fuxia Jun 13 '13 at 11:12
  • 3
    Thank you it is working and for child page I had to navigate like hits $page = get_page_by_path( 'about/child' ); – freaky Jun 13 '13 at 11:15
  • Just to clarify, get_page_by_path uses the post_name field internally, not post_slug. – colefner Apr 9 at 19:04
  • Just to be clear, this uses the page path and not the page name, correct? Then a page named "About us" the argument should be "about-us", correct? with no beginning or trailing slashes? – user658182 Jul 25 at 16:01

I've been using this ..

function get_id_by_slug($page_slug) {
    $page = get_page_by_path($page_slug);
    if ($page) {
        return $page->ID;
    } else {
        return null;
    }
} 

Hope this will help someone.

It has been already asked and answered on this forum. I am pasting the same code from there. Use this function to retrieve page id.

 function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) { 
  global $wpdb; 
   $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s AND post_status = 'publish'", $page_slug, $post_type ) ); 
     if ( $page ) 
        return get_post($page, $output); 
    return null; 
  }
  • This is perfect. Thanks! – Gavin Aug 30 '16 at 18:58

I had problems with the chosen answer when trying to use the code several times in the same page. It kept on displaying all of my pages content at the same time in every instance. So I went back to thinking and came up with this simpler approach based on the WordPress Codex's documentation:

<?php $query = new WP_Query( array( 'pagename' => 'about-me' ) );
        while ( $query->have_posts() ) {
        $query->the_post();
        echo '<h2>'. get_the_title() .'</h2>';
        the_content();
    }
    wp_reset_postdata();
?>

Maybe it can still be helpful for somebody out there ;D

<?php  function get_page_ID_by_slug( $slug ) {
    $page = get_page_by_path( $slug );
    if ( $page ) {
        return (int) $page->ID;
    }
    else {
        return null;
    }
}
?>

I hope this suggestion is helpful for someone.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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