Created
July 21, 2012 21:09
-
-
Save gyrus/3157198 to your computer and use it in GitHub Desktop.
Check if a WordPress page is "current"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Check if a WordPress page is "current", i.e. it's the current page or the ancestor of a current page | |
* | |
* @uses is_search() | |
* @uses get_post_type() | |
* @uses site_url() | |
* @uses get_permalink() | |
* @uses get_post_type_object() | |
* @uses get_permalink() | |
* @uses get_option() | |
* @param int|object $page The page object or ID | |
* @return boolean | |
*/ | |
function pilau_is_current( $page ) { | |
// Never current in a search | |
if ( is_search() ) | |
return false; | |
// Initialize | |
global $post; | |
$current = false; | |
$page_id = is_object( $page ) ? $page->ID : $page; | |
if ( $post->ID == $page_id || ( is_object( $post ) && property_exists( $post, 'ancestors' ) && is_array( $post->ancestors ) && in_array( $page_id, $post->ancestors ) ) ) { | |
$current = true; | |
} else if ( get_post_type() != "page" ) { | |
// The above does a simple check | |
// Need to account for current view being a custom post type or CPT archive | |
$page_path = trim( str_replace( site_url(), '', get_permalink( $page_id ) ), '/' ); | |
if ( get_post_type() != "post" ) { | |
$post_type_object = get_post_type_object( get_post_type() ); | |
$rewrite_slug = $post_type_object->rewrite['slug']; | |
} else { | |
$rewrite_slug = trim( str_replace( site_url(), '', get_permalink( get_option( 'page_for_posts' ) ) ), '/' );; | |
} | |
if ( strlen( $rewrite_slug ) >= strlen( $page_path ) && substr( $rewrite_slug, 0, strlen( $page_path ) ) == $page_path ) | |
$current = true; | |
} | |
return $current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment