Echo a class if current page matches the li name in wordpress

I’m trying to find some logic that will echo a class only if the current page title matches the title in the li. I’m having trouble coming up with an ‘if’ statement that won’t apply to all the li in this query.

This is in wordpress.

Read More

Here’s the context:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
   <li><a href="<?php the_permalink(); ?>" <?php if(NEED LOGIC HERE) echo 'class="current"'; ?>><?php the_title(); ?></a></li>
<?php endwhile; wp_reset_query(); endif; ?>

Any help would be much appreciated!

Related posts

2 comments

  1. If you know that you are on a single of some sort (ie. a page, post or similar), then I suppose you could save the ID of that before your custom loop and compare to that:

    global $post;
    //Make sure you are on a single, otherwise you'll get funny results
    if (is_single()) {
        $saved_id = $post->ID;
    } else {
        $saved_id = false;
    }
    
    if (have_posts()) {
        while (have_posts()) {
            the_post();
            echo '<li><a href="' . get_the_permalink() . '"';
            if($saved_id === $post->ID) {
                echo 'class="current"';
            }
            echo '>';
            the_title();
            echo '</a></li>';
        }
        wp_reset_query();
     }
    

    …sorry for changing the code style completely, I couldn’t make it readable using the template tags.

    Oh, and of course you could compare the titles instead if that is actually more desirable (though obviously less precise), just use get_the_title() or $post->post_title instead of $post-ID.

  2. Ok, I figured it out. I needed to go outside the loop to create a valid if statement that read the link in the query AND the current page. Notice the $titleID.

    <?php
        $titleID = (get_the_title());
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $parentID = (wp_get_post_parent_id( $post_ID ));
        $args= array(
            'posts_per_page' => -1,
            'post_type' => 'page',
            'post_parent' => $parentID,
            'paged' => $paged
            );
            query_posts($args);
        ?>
        <?php if (have_posts()) : while (have_posts()) : the_post(); ?> 
            <li><a href="<?php the_permalink(); ?>" <?php if(get_the_title() == $titleID ) echo 'class="current"'; ?>><?php the_title(); ?></a></li>            
        <?php endwhile; wp_reset_query(); endif; ?>
    

Comments are closed.