How to Find a WordPress Page ID by Its Name

Home » Snippets » How to Find a WordPress Page ID by Its Name

Created with:



Creator: WPTurbo Team

Customize with WPTurbo AI

Add Snippet To Project

New Project
Add To Existing Project

Have you ever wondered how you can get a page ID by its name on a WordPress website? Although it might sound a bit technical, it’s actually a handy trick than can make managing your content significantly easier. This article will guide you through the simple steps of identifying a page’s unique ID using its name. Whether you’re a seasoned web developer or a WordPress beginner, this tutorial can help streamline your website management techniques. Let’s dive in!

					function wpturbo_get_page_id_by_name($page_name) {
    $page = get_page_by_title($page_name, OBJECT, 'page');
    return $page ? $page->ID : null;

This code snippet is defining a new function called wpturbo_get_page_id_by_name(), which will fetch and return the ID of a WordPress page given its name.

The function takes one parameter, $page_name, which is expected to be the name (or title) of the page you’re looking for.

function wpturbo_get_page_id_by_name($page_name) { }

Inside the function, you’ll find get_page_by_title() WordPress function. This function takes three parameters: the title of the page, the output type, and the post type. Here, the title of the page is the $page_name input to our function, the output type is set to OBJECT, for access to property values directly and ‘page’ specifies that we are querying only ‘pages’ and not ‘posts’ or ‘attachments’, for instance.

This function is used to retrieve the entire WP_Post object for the specified page.

$page = get_page_by_title($page_name, OBJECT, 'page');

With the retrieved $page object, one can access any properties of the page including the content, the excerpt, the author, the date, and importantly for our function, the ID.

However, there’s an edge case to consider. If there’s no page found with the provided title, get_page_by_title() will return null. Thus before returning the page ID, we check to see if $page is not null.

return $page ? $page->ID : null;

If $page is not null, then we return the ID of the page i.e $page->ID; otherwise, null is returned.

This way, we have a function that will reliably return the ID of a WordPress page by its title, or notify us if no such page exists.

Register an account to save your snippets or go Pro to get more features.