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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100