while循环中的PHP第一个和最后一个类

标签 php wordpress while-loop css

我正在尝试找出如何在 while 循环输出的第一个和最后一个元素上添加第一个和最后一个类。我通过搜索发现的唯一一件事与直接使用 mysql 相关,而我在 Wordpress 循环中使用它(我放入了一个函数,我想在其中创建类 osu_first_last()):

<div id="news-loop">
    <h2 class="widget-title">News</h2>
    <?php
        // Build query for 
        $wp_news_query_temp = clone $wp_query;
        $wp_news_query = new WP_Query();
        $wp_news_query->query('category_name=News&showposts=3&orderby=date&order=DESC');
        $news_counter = 0;
        // Create posts loop
        if ($wp_news_query->have_posts()) : while ($wp_news_query->have_posts()) : $wp_news_query->the_post(); ?>
        <div class="news-entry news-entry-<?php echo $news_counter; ?><?php osu_first_last(); ?>">
            <h3 class="entry-title">
            <?php the_title(); ?>
            </h3>
            <?php twentyten_posted_dateonly(); ?>
            <?php echo osu_short_excerpt(); ?>
        </div> <!-- End div.news-entry -->
        <?php
        $news_counter++;
        endwhile; ?>
        <?php endif; $wp_query = clone $wp_news_query_temp; ?>
        <a href="<?php bloginfo('url'); ?>/category/news/" class="sidebar-more">View all news</a>   
</div>

有人可以建议最好的方法吗?

谢谢,

欧苏

最佳答案

您可以使用 current_postpost_count 并通过将其与查询一起传递给 osu_first_last() 来确定第一篇和最后一篇文章

然后像这样实现 osu_first_last()

function osu_first_last($query)
{
    $extraClass = "";
    if($query->current_post == 1)
    {
        $extraClass .= "first";
    }
    if($query->post_count == $query->current_post)
    {
        if($extraClass != "")
        {
            // post is first and last
            $extraClass .= " ";
        }
        $extraClass .= "last";
    }
    return $extraClass;
}

在你的代码中它看起来像这样:

<div class="news-entry news-entry-<?php echo $news_counter; ?><?php echo osu_first_last($wp_news_query); ?>">

关于while循环中的PHP第一个和最后一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5868330/

相关文章:

php - 如何在使用 eloquent 时排除某些列

php - 从多个条件中删除

javascript - Wordpress thickbox 元素中的 JQuery 使用

wordpress - Google Analytics(分析)中的着陆页分析和所有页面分析有什么区别

java - 创建一个java循环,当用户输入出生年份时计算用户的年龄,有什么想法吗?

php - PHP 代码中下划线的使用

php - 如何在PHP中获取strpos来匹配外文字符?

php - Wordpress:为自己的插件功能获取 $table_prefix

python - 无法正常运行 while 循环

javascript - 找到一组数字的最大值(JS)