【问题标题】:Add class to current Wordpress Post Title将类添加到当前的 Wordpress 帖子标题
【发布时间】:2018-10-16 23:29:37
【问题描述】:

我正在开发一个服务 cpt,并希望在单个帖子的同一 cpt 中显示其他帖子的列表。

我使用的代码是:

<?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>

现在我的问题是,有没有办法在当前帖子中添加一个类?目的是将其样式与列表中的其他帖子不同。

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    是的,首先获取当前帖子 id 并将该 id 与循环 id 匹配,如果它相同,则只需在您想要的任何位置添加类,只需使用下面的代码

    <?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>
    

    它只会将“current-post”类添加到当前帖子中,而在其他帖子中它不会添加任何内容。 样式使用

    <style>
    li{
    /*all posts*/
    }
    li.current-post{
    /*specific for the current post*/
    }
    </style>
    

    【讨论】:

      【解决方案2】:

      这很容易,你可以随时在之前和之后添加类

      阅读此文档https://developer.wordpress.org/reference/functions/the_title/

      <?php the_title( '<div class="wrapper">', '</div>' ); ?>
      

      【讨论】:

      • 我只希望它显示在当前帖子上,而不是全部显示。
      【解决方案3】:

      使用函数

      &lt;?php post_class(); ?&gt;

      例如:

      &lt;div &lt;?php post_class(); ?&gt;&gt;

      <?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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多