get_permalink_by_name()
2010-01-16 @ 14:53The problem
WordPress have a built in function called get_permalink. However, it only accepts an ID as an in parameter. I can’t get a permalink if I have a page / post name.
The solution
I created a function that returns an URL when sending a post / page name as an in parameter. Put the function into your functions.php in your theme folder.
function get_permalink_by_name($post_name) { global $post; global $wpdb; $id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$post_name."'"); return get_permalink($id); }
The function call
Call the function inside the loop, somewhere in your theme. The code below prints out the current user information.
echo get_permalink_by_name('my-post-name');
Improvements
Do you have any ideas, bugs, features or anything else to improve the code? Write a comment and I’ll look into it.
2010-05-04 @ 12:53 f m
I’m using this function on a page to go link back to another page, by name, within the loop, with no problems. However, on a post, within the loop, I’m not getting a permalink, it returns the current posts permalink.
Is there something I’m missing? I’m using WordPress 2.9.2.
Thanks
2011-04-30 @ 12:44 f m
This solved a problem for me – many thanks!
2011-05-27 @ 7:16 e m
This piece of code is great. But if you have made significant revisions to the page (like changing the slug) it gets messed up and shows a slug such as domain/revision-8
2013-03-14 @ 1:15 e m
This is my approach for the same problem
function get_permalink_by_title($title){
$page = get_page_by_title($title);
$pageID = $page->ID;
$permalink = get_permalink($pageID);
return $permalink;
}