doubishi8303 2015-11-03 03:51
浏览 56
已采纳

如果总数是偶数或奇数,如何计算循环中的帖子总数并创建不同的输出(WP)

So I've been looking for a solution to this for a while to no avail. There's a lot of information out there about creating a different output for even numbered posts vs odd numbered posts, but I need something differently.

Basically I have dynamically loaded posts added to a page. They are all 50% of the container with a float: left CSS rule. So if the total number of posts is even it looks great, if it's odd, there's an awkward empty space after the last post loaded to the page.

I'd like to create a rule that states if total number of post is even, apply this mark-up, if is odd, apply alternate mark up. Then I can take the last child of mark up and force the width to 100% instead of 50%.

Here's my loop:

<?php $the_query = new WP_Query();
    $x = 0;
    while ( $the_query->have_posts() ) :
        $the_query->the_post(); ?>

        <article>
            Some Content
        </article>
    <?php endwhile;
    $x++;
wp_reset_query(); ?>

CSS:

article { width: 50%; float: left; }

What I want is:

<?php if ($post_count = even) : ?>
    <article>
        Some Content
    </article>
<?php elseif ($post_count = odd) : ?>
    <article class="alt">
        Some Content
    </article>
<?php endif; ?>

CSS:

article { width: 50%; float: left; }
article.alt:last-child { width: 100%; }

Is anyone familiar with how this can be achieved? As always, any help is greatly appreciated!

cheers,

  • 写回答

2条回答 默认 最新

  • douzhang5121 2015-11-03 03:58
    关注

    You can try this :

    $count_posts = wp_count_posts();
    $published_posts = $count_posts->publish;
    if($published_posts % 2 == 0) 
    {
        // even
    }
    else
    {
        //odd
    }
    

    If you want to know whether respective post is even or odd...please refer to below :

    <?php $postnum = 0;?>
        if (have_posts()) : while (have_posts()) : the_post(); ?>
    
    <?php $postnum++;
        $alt = ( $postnum % 2 ) ? ' even_post' : ' odd_post';
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?