maxyudin

Wordpress | Get post ID from custom post type URLs

Nov 9th, 2012
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.05 KB | None | 0 0
  1. /* http://sltaylor.co.uk/blog/get-post-id-from-custom-post-types-urls/ */
  2. function url2PostId( $url ) {
  3.     // Try the core function
  4.     $post_id = url_to_postid($url);
  5.     if ($post_id == 0) {
  6.         // Try custom post types
  7.         $cpts = get_post_types( array(
  8.             'public'   => true,
  9.             '_builtin' => false
  10.         ), 'objects', 'and' );
  11.         // Get path from URL
  12.         $url_parts = explode( '/', trim( $url, '/' ) );
  13.         $url_parts = array_splice( $url_parts, 3 );
  14.         $path = implode( '/', $url_parts );
  15.         // Test against each CPT's rewrite slug
  16.         foreach ( $cpts as $cpt_name => $cpt ) {
  17.             $cpt_slug = $cpt->rewrite['slug'];
  18.             if ( strlen( $path ) > strlen( $cpt_slug ) && substr( $path, 0, strlen( $cpt_slug ) ) == $cpt_slug ) {
  19.                 $slug = substr( $path, strlen( $cpt_slug ) );
  20.                 $query = new WP_Query( array(
  21.                     'post_type'            => $cpt_name,
  22.                     'name'                => $slug,
  23.                     'posts_per_page'    => 1
  24.                 ));
  25.                 if ( is_object( $query->post ) )
  26.                     $post_id = $query->post->ID;
  27.             }
  28.         }
  29.     }
  30.     echo '-' . $post_id . '<br />';
  31.     return $post_id;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment