Get Page ID or URL From a Slug in WordPress

Last Updated: January 11, 2021 | Reading Time: < 1 minute

This is interesting, with years experience working with WordPress, I’ve never dealt with this kind of issue. I searched the codex, and found get_page_by_path is the ideal solution instead of directly create query to database.

get_page_by_path( $page_path, $output, $post_type );

To get a page ID simply add the slug to the function

// Returns Object page ID
$page_id = grain_get_url_by_slug('slug');

I creates a function to simplify the usage

function get_url_by_slug($slug) {
    $page_url_id = get_page_by_path( $slug );
    $page_url_link = get_permalink($page_url_id);
    return $page_url_link;
}

And use it in real life

<p>
	<a href="<?php echo get_url_by_slug('services'); ?> ">
		What can we do for you?
	</a>
</p>

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

    Any idea? Fill the comment below

    This site uses Akismet to reduce spam. Learn how your comment data is processed.