Getting Page ID Inside Loop

Building custom menus and filters is unavoidable. If you’re not comfortable triggering the active item with jQuery to add an active class, you can find the current page ID, and use existing WordPress CSS classes to reapply styles already within your stylesheet.

Check out the custom menu below:

<ul class="top_menu">
	<?php
	
	global $post;
	$page_id = get_queried_object_id(); // current page ID
	
	$args = array(
	  'orderby' => 'menu_order',
	  'order' => 'asc',
	  'post_type' => 'page',
          'post_parent' => 47
	);
	
	$page = new WP_Query($args);
	
	while($page->have_posts()) : $page->the_post(); 
						
		if( $page_id === $post->ID ) { // check if current page ID is equal to current menu item ?>
	
			<li class="current_page_item"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
		
		<?php } else { ?>
			
			<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
		
		<?php } ?>
			
	<?php endwhile; wp_reset_query(); ?>
</ul><!-- .top_menu -->

 

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.