Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Created April 20, 2015 15:43
Show Gist options
  • Save mcaskill/5a2b6bae257f4fe60e11 to your computer and use it in GitHub Desktop.
Save mcaskill/5a2b6bae257f4fe60e11 to your computer and use it in GitHub Desktop.
WordPress : Retrieve a post ID given its path.
<?php
if ( ! function_exists('get_ID_by_path') ) :
/**
* Retrieves an ID given its path.
*
* @global $wpdb
*
* @param string $page_path Page path
* @param string $post_type Optional. Post type. Default page.
* @return mixed Null when complete.
*/
function get_ID_by_path ( $page_path, $post_type = 'page' )
{
$page_path = rawurlencode( urldecode( $page_path ) );
$page_path = str_replace( '%2F', '/', $page_path );
$page_path = str_replace( '%20', ' ', $page_path );
$parts = explode( '/', trim( $page_path, '/' ) );
$parts = array_map( 'esc_sql', $parts );
$parts = array_map( 'sanitize_title_for_query', $parts );
$in_cache = implode( ',', $parts );
$cached_id = wp_cache_get( 'get_id_by_path_' . $in_cache, 'skl-posts' );
if ( $cached_id ) {
return $cached_id;
}
$q = get_queried_object();
if ( isset( $q->post_name ) && $q->post_name == end( $parts ) ) {
$found_id = $q->ID;
}
else {
global $wpdb;
reset( $parts );
$in_string = "'". implode( "','", $parts ) . "'";
$post_type_sql = $post_type;
$wpdb->escape_by_ref( $post_type_sql );
$sql = "
SELECT ID, post_name, post_parent
FROM $wpdb->posts
WHERE post_name IN ($in_string)
AND (post_type = '$post_type_sql'
OR post_type = 'attachment')
";
$pages = $wpdb->get_results( $sql, OBJECT_K );
$revparts = array_reverse( $parts );
$found_id = 0;
foreach ( (array) $pages as $page ) {
if ( $page->post_name == $revparts[0] ) {
$count = 0;
$p = $page;
while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
$count++;
$parent = $pages[ $p->post_parent ];
if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
break;
$p = $parent;
}
if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
$found_id = $page->ID;
break;
}
}
}
}
wp_cache_set( 'get_id_by_path_' . $in_cache, $found_id, 'skl-posts' );
return $found_id;
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment