php - 如果 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++;
?>
<div class="col-custom <?php if ($counter >= 4): echo 'col-sm-6'; endif; ?>">
<article id="<?php echo get_the_ID(); ?>" class="news__block <?php echo $post_class; ?>" <?php if(!empty($post_img_url) && has_category('nieuws')): ?> style="background-image: url('<?php echo $post_img_url; ?>');" <?php endif; ?>>
<div class="news__container">
<header class="news__header">
<h3 class="news__pretitle"><?php echo $post_category; ?> <?php if(has_category('nieuws')): echo '- ' . $post_date; endif; ?></h3>
<h2 class="news__title"><?php echo $post->post_title; ?></h2>
<?php if($post->post_excerpt): ?>
<p class="news__message"><?php echo $post->post_excerpt; ?></p>
<?php endif; ?>
</header>
<a href="<?php echo get_post_permalink(); ?>" class="news__link">Lees meer</a>
</div>
</article>
</div>
<?php endif; ?>
<?php endforeach; ?>
</div>
</div>
</section>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
解决方案
我假设您正在尝试显示col-sm-6
大于 4 的帖子的类。
有几件事,你可以做它来使它工作。
- 删除循环
$counter
后递增的代码。foreach
我们将在下面的第 2 步中执行此操作。
foreach( $posts as $post):
//$counter++; This should be commented.
- 相反,我们应该
if
在您检查状态的块内增加这个计数器。
if ('publish' === $post->post_status):
//echo $counter; //Comment this out
$counter++; //increment it here
?>
- 最后一步是确保当
$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; ?>">
推荐阅读
- python - GEKKO多元非线性回归
- spring-boot - 在 Spring ElasticSearch Data 中找不到类 EntityMapper
- python - 在python中将多值字典转换为数据框
- node.js - 如何处理我已经构建的 react 应用程序?
- file - 检查目录中是否存在多个文件时需要二进制运算符
- r - 闪亮的文件输入接受所有文件类型
- http - Postman 用隐形 reCaptcha 模拟登录网站
- mysql - 无法从 kubernetes 连接到本地计算机上的 mysql
- spring-boot - SpringBoot restcontroller如何防止并发访问
- apache-spark - 当我将 event_timestamp 列从字符串转换为时间戳时,PySpark(version 3.0.0) to_timestamp 返回 null