WordPress Snippets at WPcustoms

Return permalink with page slug

A handy snippet if you need to use a permalink url in your theme files. You can use get_permalink(3) where 3 is the ID but if you got a local dev the ID won’t match with the online ID. This function solves the problem by using the page slug which is unique. It returns the permalink from your defined page slug.


/**
 * Snippet Name: Return permalink with page slug
 * Snippet URL: https://wpcustoms.net/snippets/return-permalink-with-page-slug/
 */
  // usage: echo get_permalink( wpc_get_ID_by_slug('my-page-slug') );

function wpc_get_ID_by_slug($page_slug) {
    $page = get_page_by_path($page_slug);
    if ($page) {
        return $page->ID;
    } else {
        return null;
    }
}