Skip to content

Instantly share code, notes, and snippets.

@kmwalsh
Forked from gyrus/gist:3157198
Created September 9, 2020 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmwalsh/aeaf0b2115660154affcc146fcb8e319 to your computer and use it in GitHub Desktop.
Save kmwalsh/aeaf0b2115660154affcc146fcb8e319 to your computer and use it in GitHub Desktop.
Check if a WordPress page is "current"
<?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