If permalink is equal to current site url

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="https://wordpress.stackexchange.com/questions/88833/<?php the_permalink() ?>">
          <?php the_title() ?>
       </a>
   </li>

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

1 Answer
1

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="https://wordpress.stackexchange.com/questions/88833/<?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.

Leave a Comment