Easiest way to simulate WordPress’s URL resolution to retrieve post ID, etc?

I’m curious if it is possible, in a plugin/custom code, to take an URL that has been generated by the currently running WordPress site & parse it to retrieve the $blog_id and $post_id?

ie. taking a string like “myblog.mysite.com/2012/03/16/whatever/” and determining that this is post #6 (“whatever”) on blog #2 (“myblog”).

Read More

I realize that I can probably strip the URL and parse the domain myself, but I hope that there might be recommended WordPress methods exposed to make this more robust across URL formats.

Related posts

Leave a Reply

3 comments

  1. As Weston mentioned, if you’re within WordPress and you know what blog the URL came from, then ask WordPress for the blog ID.

    But if you’re really, really sure there’s no better method in this case than parsing a URL, then here you go:

    $url = 'http://myblog.mysite.com/2012/03/16/whatever/';
    
    $domain = parse_url( $url, PHP_URL_HOST );
    
    // This could be dynamic but good enough for now
    $subdomain = str_replace( '.mysite.com', '', $domain );
    
    // Never use $blog_id for anything, you'll break tons of things
    $parsed_blog_id = get_id_from_blogname( $subdomain );
    
    
    // url_to_postid() only works for the current blog
    switch_to_blog( $parsed_blog_id );
    
    $post_id = url_to_postid( $url );
    
    restore_current_blog();
    

    Reference material:

    http://codex.wordpress.org/Function_Reference/get_id_from_blogname

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