Add class to current Wordpress Post Title

2019-08-27 06:22发布

I am working on a services cpt and would like to display a list of other posts, within the same cpt on the single post.

The code I am using is:

<?php 
    $loop = new WP_Query( array( 
        'post_type' => 'services', 
        'posts_per_page' => 6
    ));
?>
<ul>
    <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                <h4><?php the_title(); ?></h4>
            </a>
        </li>
    <?php endwhile; wp_reset_query(); ?>
</ul>

Now my question is, is there a way to add a class to the current post? The intention being to style it different to the other posts in the list.

3条回答
放我归山
2楼-- · 2019-08-27 06:41

Using function

<?php post_class(); ?>

E.g:

<div <?php post_class(); ?>>

<?php 
  $loop = new WP_Query( array( 
    'post_type' => 'services', 
    'posts_per_page' => 6
  ));
?>
<ul>
  <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <li <?php post_class(); ?>>
      <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
        <h4><?php the_title(); ?></h4>
      </a>
    </li>
  <?php endwhile; wp_reset_query(); ?>
</ul>
查看更多
疯言疯语
3楼-- · 2019-08-27 06:53

This is very easy you can always add the class in before and after

Read this documentation https://developer.wordpress.org/reference/functions/the_title/

<?php the_title( '<div class="wrapper">', '</div>' ); ?>
查看更多
Animai°情兽
4楼-- · 2019-08-27 07:00

Yes First get current post id and match that id with loop id and if it is same than just add class whereever you want just use below code

<?php 
$current_post_id = get_the_ID();
$loop = new WP_Query( array( 
    'post_type' => 'services',
    'posts_per_page' => 6, ));
?>
<ul>
   <?php 
   while ( $loop->have_posts() ) : $loop->the_post();
       $class = ($current_post_id == $loop->ID) ? "current-post" : '';
   ?>
   <li class="<?php echo $class; ?>">
     <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
         <h4><?php the_title(); ?></h4>
     </a>
   </li>
   <?php endwhile; wp_reset_query(); ?>
</ul>

It will add class "current-post" to only current post and in other posts it will add nothing. style using

<style>
li{
/*all posts*/
}
li.current-post{
/*specific for the current post*/
}
</style>
查看更多
登录 后发表回答