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

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



Solution 1:[1]

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');

Solution 2:[2]

2022 update

url_to_postid( string $url )

For reference: http://codex.wordpress.org/Function_Reference/url_to_postid

Solution 3:[3]

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

Solution 4:[4]

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;
}

Solution 5:[5]

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,

Solution 6:[6]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Hariprasad
Solution 4 khandaniel
Solution 5 jovaniwayne
Solution 6 Sulthan Allaudeen