Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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(); ?>
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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.

share|improve this answer
    
That's awesome! Thanks! –  Wnd Feb 28 '13 at 19:08
    
You're welcome. I'm doing a small editing for not echoing nothing. –  Simon Feb 28 '13 at 20:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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