如果总数是偶数或奇数,如何计算循环中的帖子总数并创建不同的输出(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,

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

the modulus (%) operator can be used here

if (($x % 2) == 1)
{
  echo "odd";
}

if (($x % 2) == 0)
{
  echo "even";
}

See: php test if number is odd or even