0

In my menu I have a page that is called Campaign.

When the user enters to Campaign the page displays the last custom post type of campaign-post.

In the sidebar of Campaign page, I'm displaying a list of all campaign-post custom posts.

The problem is that I don't know how to highlight (add current class) to the last post title in the list that is displayed when the user enters to Campaign page.

This is how I'm displaying the list:

<ul class="post-list">
    <?php $query = new WP_Query( array( 'post_type' => 'campaign-post' ) );         
        while ( $query->have_posts() ) : $query->the_post();
        echo '<li><a href="';
        the_permalink();
        echo '">';
        the_title();
        echo '</a></li>';
    endwhile; ?>
</ul>

Any ideas?

2

That's easy: You should use $wp_query->current_post to retrieve the index of your custom query.

In your case query will work something like this:

<ul class="post-list">
    <?php $query = new WP_Query( array( 'post_type' => 'campaign-post' ) );         
    while ( $query->have_posts() ) : $query->the_post();
            if($query->current_post == 0){
        ?>
            <h1 class="current"><?php the_title(); ?></h1>
        <?php
        }
        else{   
        ?>
            <h1 class="normal"><?php the_title(); ?></h1>
        <?php
        }
     endwhile; ?>
</ul>

You can customize it more that suits to your need.

How it works? You may have noticed that there is a while loop which proceeds the results (posts retrieved from the query) one by one. If somehow we get to know that this is first post then we can use the if-else structure to extract it and customize. Fortunately $wp_query->current_post tells us about the post index.

You can do this too: More customization.

CODE EDITED:

if($query->current_post == 0){
    ?>
        <h1 class="current"><?php the_title(); ?></h1>
    <?php   
    }
    elseif ($query->current_post == 1){
?>
    <h2 class="second-post"><?php the_title(); ?></h2>
<?php
    }
    else{
    ?>
        <h3 class="rest-posts"><?php the_title(); ?></h3>
    <?php

    }
  • Thanks Sudeep but if I put your first code it adds current class to all the custom posts that are displayed on the list. If I put your second code then none has the current class – wpuser Feb 12 '14 at 0:24
  • @diego : My bad. I pasted the code from my textpad and didn't realize that your custom query array is $query. Hope edited code will work now. – Sudeep K Rana Feb 12 '14 at 4:36
0

Use the :last-child selector in your style.css to style only the last list tag found within the post-list class.

ul.post-list li:last-child {
/* This styling should only affect the last <li> tag in the list*/
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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