【问题标题】:How can I add an "active" class to post title in a list of posts?如何在帖子列表中添加“活动”类来发布标题?
【发布时间】:2013-06-08 16:50:40
【问题描述】:

我有一个 Wordpress 食谱博客,它为用户提供“早餐”和“午餐”的食谱。每个食谱都是一个单独的 Wordpress 自定义帖子类型,标记为“早餐”或“午餐”。 (我使用的是标签,而不是类别,因为我不会进入。)自定义帖子类型称为“食谱”。

如果用户在标记为“早餐”的帖子上,他们会看到所有其他标记为“早餐”的帖子的列表。我通过查询(使用 WP_Query)所有标记为“早餐”的帖子并在列表中显示这些帖子的标题来创建此列表。标题还链接到相应的帖子,因此用户可以在阅读带有“早餐”标签的帖子时跳转到任何带有“早餐”标签的帖子。

我的问题:如何在与我当前正在阅读的帖子相对应的帖子标题中添加“活跃”类? (所以如果我在标题为“培根”的帖子上,我的“早餐”标签帖子列表中的标题“培根”应该有一个“活动”类。下面是我在单曲中使用的代码.php 页面按标签生成我的帖子列表:

<?php if (has_tag( 'breakfast' )) { ?>
    <?php $loop = new WP_Query( array( 'post_type' => 'recipes', 'tag' => 'breakfast') ); ?>
    <ul>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <li>
            <?php the_title( '<a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a>' ); ?>
            </li>
            <?php endwhile; ?>
            <?php wp_reset_query(); ?>
    </ul>
<?php } elseif (has_tag( 'lunch' )) { ?>
    <?php $loop = new WP_Query( array( 'post_type' => 'recipes', 'tag' => 'lunch') ); ?>
    <ul>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <li>
            <?php the_title( '<a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a>' ); ?>
            </li>
            <?php endwhile; ?>
            <?php wp_reset_query(); ?>
    </ul>
<?php } else { ?>
<?php } ?>

【问题讨论】:

    标签: wordpress tags


    【解决方案1】:

    在自定义查询之前,将当前帖子的 ID 放在一个 var 中:

    $temp = get_the_ID();
    

    然后,在您的自定义循环中,检查 ID 是否匹配:

    $class = ( $temp == get_the_ID() ) ? 'active' : '';
    

    并将适当的类应用于标题:

    class="' . $class . '"
    

    【讨论】:

      猜你喜欢
      • 2013-05-28
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-10
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多