I am working on a WordPress project and I need to get the page URL by the title of the page. I used to use the function get_page_by_title ($article [‘title’], OBJECT, ‘post’) to do this, but I found out that this function has been deprecated and is no longer recommended. This function was very convenient for me because I was testing some features on different databases and I could not use IDs to get the page URL. Is there any alternative way to get the page URL by the title of the page in WordPress without using IDs or WP_Query class? I think using WP_Query class is too complicated and inefficient for this simple task. I would appreciate any suggestions or solutions that can help me with this problem. Thank you.
Share
One possible way to get the page URL by the title of the page in WordPress without using IDs or WP_Query class is to use the function get_page_link_by_title ($title). This function takes the title of the page as a parameter and returns the URL of the page if it exists, or false if it does not. The function uses the global $wpdb object to query the database and get the ID of the page by its title, then uses the function get_permalink ($id) to get the URL of the page by its ID. Here is an example of how to use this function:
function get_page_link_by_title ($title) {
global $wpdb;
$id = $wpdb->get_var (“SELECT ID FROM $wpdb->posts WHERE post_title = ‘$title’ AND post_type = ‘page'”);
if ($id) {
return get_permalink ($id);
} else {
return false;
}
}
// Usage example
$page_title = “About Us”;
$page_url = get_page_link_by_title ($page_title);
if ($page_url) {
echo “The URL of the page ‘$page_title’ is $page_url”;
} else {
echo “The page ‘$page_title’ does not exist”;
}
I hope this function helps you with your WordPress project. Please note that this function does not sanitize the title parameter, so you should make sure that it does not contain any malicious or invalid characters before passing it to the function. Also, this function assumes that there is only one page with the given title in the database, so it may not work correctly if there are duplicate titles. You may want to modify the function to handle these cases according to your needs.