Wordpress - how to get page id of a page using page slug

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.
Documentation:
https://developer.wordpress.org/reference/functions/get_page_by_path/
https://developer.wordpress.org/reference/functions/get_the_title/


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; 
  }

Tags:

Php

Slug

Id