Get a WordPress Page ID with the Slug

When I develop for WordPress, I start out on my local machine, then eventually migrate to the production server. This works very well, but takes a bit more work when I get to the migration stage. To make it a little easier, I use this little function to eliminate any hard-coded page IDs in navigation links or conditional statements:

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

Then, whenever we need to call a function that requires a page ID, just pass it our new function.

wp_some_function(get_ID_by_slug('any-page'));

Notes

  1. tagthis reblogged this from erikt
  2. propz reblogged this from erikt
  3. earnmoneywithoutinvestment reblogged this from erikt
  4. erikt posted this