2

Is there a way to add a class to a div, when the current site url is equal to the permalink of a post?

I need a class "current" to my custom made menu. I put the posts links in a list item with a loop, and for every link i want to check if the permalink is equal to the current page url. If the permalink matches the current page url, i want to add the class "current".

Something like:

<?php $currentUrl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>
<?php if ( $currentUrl == the_permalink() ) { echo ' class="current"'; } else {} ?>

Together with the loop:

<?php $currentUrl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>

<?php query_posts('orderby=name'); ?>
<?php while (have_posts()) : the_post(); ?>

   <li>
       <a <?php if ( $currentUrl == the_permalink() ) { echo ' class="current"'; } else {} ?>
       href="<?php the_permalink() ?>">
          <?php the_title() ?>
       </a>
   </li>

<?php endwhile; ?>
<?php wp_reset_query(); ?>
4

I would do something simplier using ID :

<?php $current_id = $post->ID; ?>
<?php query_posts('orderby=name'); ?>  
<?php while (have_posts()) : the_post(); ?>

   <li>
       <?php $current_class = ( $current_id == $post->ID ) ? 'class="current"' : ''; ?>
       <a <?php if ( $current_class ) echo $current_class; ?> href="<?php the_permalink() ?>">
          <?php the_title() ?>
       </a>
   </li>

<?php endwhile; ?>
<?php wp_reset_query(); ?>

I didn't had time to verify code, hope this helps.

  • You're welcome. I'm doing a small editing for not echoing nothing. – Simon Feb 28 '13 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.