Steve Taylor photo

Get post ID from custom post type URLs as well

url_to_postid is a great core WordPress function. Give it a URL (from your own site!) and it’ll return the ID of the post or page it refers to. I’m using it so clients can paste a URL into a custom field (easy for them), then I can get other stuff related to the content using the ID (easy for me).

But it doesn’t seem to handle custom post type URLs. So I wrote a little workaround…

function slt_url_to_postid( $url ) {
	// Try the core function
	$post_id = url_to_postid( $url );
	if ( $post_id == 0 ) {
		// Try custom post types
		$cpts = get_post_types( array(
			'public'   => true,
			'_builtin' => false
		), 'objects', 'and' );
		// Get path from URL
		$url_parts = explode( '/', trim( $url, '/' ) );
		$url_parts = array_splice( $url_parts, 3 );
		$path = implode( '/', $url_parts );
		// Test against each CPT's rewrite slug
		foreach ( $cpts as $cpt_name => $cpt ) {
			$cpt_slug = $cpt->rewrite['slug'];
			if ( strlen( $path ) > strlen( $cpt_slug ) && substr( $path, 0, strlen( $cpt_slug ) ) == $cpt_slug ) {
				$slug = substr( $path, strlen( $cpt_slug ) );
				$query = new WP_Query( array(
					'post_type'			=> $cpt_name,
					'name'				=> $slug,
					'posts_per_page'	=> 1
				));
				if ( is_object( $query->post ) )
					$post_id = $query->post->ID;
			}
		}
	}
	return $post_id;
}

I’ve had to alter it a little from the code I’m using. My code works, but if I’ve goofed in getting it ready for public consumption, please let me know!

UPDATE 6/2/12: Some people have reported issues with this code that I haven’t had time to investigate. If it’s not working for you, I’ve been told this function does this trick as well.

One comment

  1. Dan Farrow avatar Dan Farrow

    Steve, once again you’ve drawn attention to an amazing WP feature I never knew existed.

    And your workaround seems equally amazing – thanks for sharing it! I’ll give it a try

    Dan

Comments are closed.