如果 PHP 计数器等于 WordPress 回显类中的 4 个项目无法正常工作

我正在使用 WordPress 和高级自定义字段。我为每个循环创建了一个,一切正常。但是我不希望显示具有“草稿”状态的帖子这也可以,但是如果帖子的数组长度等于或大于 4 个帖子,我想显示一个不同的 HTML 类“col-sm-6”但这不起作用。


基本上,如果帖子已发布且数组长度等于 4,则更改类,否则什么也不做。但由于某种原因,它没有按应有的方式工作。


有人可以帮我吗?


我的代码:


<?php

$posts = get_field('home_add_news');

$counter = 0;

if($posts):

?>


<section id="news">

    <div class="container">

        <div class="row">

            <?php

            foreach( $posts as $post):

            $post_date = get_the_date( 'd M Y' );

            $post_img_url = get_the_post_thumbnail_url($post->ID, 'full');

            $post_categories = get_the_category( $post->ID );

            $post_category = $post_categories[0]->cat_name;

            $post_class = '';


            if(has_category('nieuws')):

                $post_class = 'news__block--image';

            elseif(has_category('project')):

                $post_class = 'news__block--primary';

            elseif(has_category('proces')):

                $post_class = 'news__block--secondary';

            elseif(has_category('tijdlijn')):

                $post_class = 'news__block--tertiary';

            else:

                $post_class = 'news__block--tertiary';

            endif;


            if ('publish' === $post->post_status):

            $counter++;

            ?>


拉丁的传说
浏览 123回答 1
1回答

萧十郎

我假设您正在尝试显示col-sm-6大于 4 的帖子的类。有几件事,你可以做它来使它工作。删除循环$counter后递增的代码。foreach我们将在下面的第 2 步中执行此操作。&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach( $posts as $post):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //$counter++; This should be commented.相反,我们应该if在您检查状态的块内增加这个计数器。&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ('publish' === $post->post_status):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//echo $counter;&nbsp; //Comment this out&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$counter++;&nbsp; //increment it here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ?>最后一步是确保当$counter大于或等于 4 时显示我们的类。正如@Kaperto 所建议的,您不需要在draft此处检查状态,因为您已经在检查上述状态。所以取出以下行<div class="col-custom <?php if ('draft' != $post->post_status && $counter == 4): echo 'col-sm-6'; endif; ?>">并将其更改为<div class="col-custom <?php if ($counter >= 4): echo 'col-sm-6'; endif; ?>">
打开App,查看更多内容
随时随地看视频慕课网APP