Support » Themes and Templates » Adding class to current post in sidebar

  • Resolved steverydz

    (@steverydz)


    In my single custom_post_type template I have the post displayed on the left and on the right a list of all other posts from that custom_post_type.

    I want to dynamically add a class to the list item of the current post so I can style it differently.

    Basically I want:

    <ul>
        [if is the current post]
        <li class="current"><?php the_title(); ?></li>
        [else]
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    </ul>

    I hope this is easy enough to understand?

Viewing 2 replies - 1 through 2 (of 2 total)
  • grab the post id of the current post in the main section (put it into a variable, maybe needs to be a global variable); and compare it with the post id of each post in your sidebar list; if they are the same, output ‘current’ as a class to your list item.

    Thread Starter steverydz

    (@steverydz)

    Cheers, that solved it. Here’s the code I used:

    <?php get_header(); ?>
    
    	<div id="content" class="group">
    		<div id="content-pri">
    <?php if (have_posts()) : while (have_posts()) : the_post(); $current_project = get_the_ID(); ?>
    			<h2 class="entry-title"><?php the_title(); ?></h2>
    			<?php the_content(); ?>
    <?php endwhile; endif; ?>
    		</div> <!-- // #content-pri -->
    		<aside>
    			<h3>Recent projects</h3>
    			<ul>
    <?php $loop = new WP_Query(array('post_type' => 'portfolio')); while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <?php if ( $post->ID == $current_project ) { ?>
    				<li class="current-project"><?php the_title(); ?></li>
    <?php } else { ?>
    				<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php } ?>
    <?php endwhile; ?>
    			</ul>
    		</aside>
    	</div> <!-- // #content -->
    
    <?php get_footer(); ?>

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Adding class to current post in sidebar’ is closed to new replies.