How to get post id from permalink (pretty url)?

How to get post id from permalink (pretty url)?


You should be fine with url_to_postid()[see documentation] which is located in rewrite.php. I used it in a plugin of mine last year, works like a charm.


I've got a dedicated (& documented) function for that:

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

Retrieves a page given its path.

Where $page_path is

[...] the equivalent of the 'pagename' query, as in: 'index.php?pagename=parent-page/sub-page'.

See Function Reference/get page by path

Example:

// Assume 'my_permalink' is a post.
// But all types are supported: post, page, attachment, custom post type, etc.
// See http://codex.wordpress.org/Post_Types
get_page_by_path('my_permalink', OBJECT, 'post');

This works for regular post types AND custom post types. url_to_postid() only works for regular posts.


url_to_postid() as of 3.7.0: This function now supports custom post types (see Trac tickets #19744, #25659).