How to get page id from page name wordpress

Hello friends, welcome to my another blog post how to get page id from page name WordPress. If you have your page name or page title and you need to find page id from that, WordPress does not have any default function for that. Where you pass the page name or page title and get your respective page id. Here I create a custom function for you to get page id from page name and page title. You can use my function with wp_list_pages WordPress function to be excluded from the list of pages or included your specific page.

Get page id from page name(page alias) WordPress

function get_ID_by_page_name($page_name) {
	global $wpdb; 
	$emptyarray= array();
	if(is_array($page_name)){ 
		$i=0;
		foreach($page_name as $page){
			$sql = "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_name ='".$page."' AND post_type = 'page'";
			$emptyarray[$i]=$wpdb->get_var($sql);
			$i++;
		} 
		return  $emptyarray;
	}else{
		return  $emptyarray;
	}
}





Use of the above function

$pagename = array('about-me','contact-me','hire-me'); 
if(is_array(get_ID_by_page_name($pagename)) && count(get_ID_by_page_name($pagename)>0))
{
	$pageid = implode(",",get_ID_by_page_name($pagename)); 
	echo $pageid;
}

Suppose your ‘about-me’ page id=8, ‘contact-me’ page is=11, ‘hire-me’ page id=16 then you have 8,11,16 in $pageid variable.
Now the actual use is given below :

<?php wp_list_pages('include='.$pageid); ?>
OR
<?php wp_list_pages('exclude='.$pageid); ?>

Get page id from page title WordPress

function get_ID_by_page_title($page_title) {
	global $wpdb; 
	$emptyarray= array();
	if(is_array($page_title)){ 
		$i=0;
		foreach($page_title as $page){
			$sql = "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_title ='".$page."' AND post_type = 'page'";
			$emptyarray[$i]=$wpdb->get_var($sql);
			$i++;
		} 
		return  $emptyarray;
	}else{
		return  $emptyarray;
	}
}

Use of the above function

$pagetitle = array('About Me','Contact Me','Hire Me'); 
if(is_array(get_ID_by_page_title($pagetitle)) && count(get_ID_by_page_title($pagetitle)>0))
{
	$pageid = implode(",",get_ID_by_page_title($pagetitle)); 
	echo $pageid;
}

And the rest of the task is same as getting page id from page name(page alias) WordPress section.

Thank you for your time. Now you know how to get page id from page name WordPress. Please comment below if you have any issue.

Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •