0

I have a custom post type called 'product'. On each product page I would like to have a sidebar with all products listed. The current product in the sidebar should be underlined.

When visiting product 3 for example, product 3 should be highlighted:

Sidebar

Product 1
Product 2
Product 3
Product 4

I figured a solution could be a wp-menu containing all products and then use .current-menu-item class to achieve the highlighting. But the sidebar has to be updated automatically when new products are created.

Below is my way of listing all products. Is there a way of integrating a .current-menu-item functionality?

<?php $loop = new WP_Query( array( 'post_type' => 'product' ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

<?php endwhile; ?>

By adding a class like this?

<a class="current-product" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

1 Answer 1

1

Yes, there is an easy way to achieve this.

Here is a modified version of the code that does your thing:

<?php 
// get the current product ID
$current_post_id = get_the_ID();

$loop = new WP_Query( array( 'post_type' => 'product' ) );
while ( $loop->have_posts() ) {
    $loop->the_post(); 
    ?>
    <a href="<?php the_permalink(); ?>" <?php echo get_the_ID() == $current_post_id ? 'class="current-product"' : ''; ?>><?php the_title(); ?></a>
    <?php 
}
?>

Here we basically save the ID of the current product in a variable, and then for each product of the list we check if the looped product ID is equal to the current product ID. And if it is, we display the class="current-product" attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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