how to get page id of a page using page slug

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.

4

Answers


  1. D'Tails
    0 Votes

    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

  2. Ibnul Hasan
    0 Votes

    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.

  3. Vikas Bhardwaj
    0 Votes

    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; 
      }
    
  4. toscho
    0 Votes

    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.

Please signup or login to answer this question.

Signup for an account and start participating in our site today!




Social Signup

You can also login with your Facebook, Twitter or Linkedin account

Log in with Facebook