Reputation: 11981
How to get post id from permalink (pretty url)?
Upvotes: 48
Views: 64656
Reputation: 2286
2022 update
url_to_postid( string $url )
For reference: http://codex.wordpress.org/Function_Reference/url_to_postid
Upvotes: 9
Reputation: 305
I have a multisite WP so once I go through the blogs for some reasons in some blogs url_to_postid()
works, in other blogs on the post of the same type it doesn't while get_page_by_path()
works like charm. So I made it this way, which may be not perfect though:
$parsed_url = wp_parse_url( $url ); // Parse URL
$slug = substr($parsed_url['path'], 1 ); // Trim slash in the beginning
$post_id = url_to_postid( $slug ); // Attempt to get post ID
if ( ! $post_id ) { // If it didn't work try to get it manually from DB
$post_query_result =
$wpdb->get_row("SELECT ID FROM {$wpdb->prefix}posts WHERE post_name = '{$slug}'");
$analog_id = (int) $post_query_result->ID;
}
Upvotes: 1
Reputation: 32602
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.
Upvotes: 59
Reputation: 11
please use
$postid = url_to_postid( $url );
to retrive the ID of an attachment.
It is required that the url provided be in the format of example.com/?attachment_id=N
and will not work with the full URL to get the id from the full URL.
Upvotes: 1
Reputation: 21
url_to_postid()
as of 3.7.0
: This function now supports custom post types (see Trac tickets #19744
, #25659
).
Upvotes: 2
Reputation: 21
you can try this one also:
$post = get_page_by_path('cat',OBJECT,'animal');
cat is the one you are looking for= the permalink; animal is the custom post type,
Upvotes: 0
Reputation: 1254
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');
Upvotes: 11