php - Wordpress 循环生成相同名称的列表元素,如果帖子编号较少,则查询
问题描述
我有一个最近 4 个帖子的列表,但如果我的帖子少于 4 个,则不会生成 4 个 li 元素。当posts_per_page 小于4 时,有没有办法创建一个带有空li 元素的lopp?
<ul class="slider sp">
<?php
$ids = get_field('related', false, false);
$query_args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'post__in' => $ids,
'orderby' => 'post__in',
);
$query = new WP_Query( $query_args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
$thumbnail = get_field('image0');
if(empty($thumbnail)){ $thumbnail = APP_URL . "images/cms/no-image.png"; $borderclass = "hasborder";}
?>
<li>
<a href="<?php echo get_permalink(); ?>">
<div class="imager">
<div class="img" style="background-image: url(<?php echo $thumbnail; ?>);"></div>
</div>
<p class="ttl">
<?php echo get_the_title(); ?>
</p>
<p class="price"><?php echo the_field('a-price'); ?>円(税別)</p>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
解决方案
你可以检查帖子数
<?php $count = $custom_posts->post_count; ?>
那么如果计数小于 4,你可以根据它打印剩余的 li
<ul class="slider sp">
<?php
$ids = get_field('related', false, false);
$query_args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'post__in' => $ids,
'orderby' => 'post__in',
);
$query = new WP_Query( $query_args );
$count = $query->post_count;
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
$thumbnail = get_field('image0');
if(empty($thumbnail)){ $thumbnail = APP_URL . "images/cms/no-image.png"; $borderclass = "hasborder";}
?>
<li>
<a href="<?php echo get_permalink(); ?>">
<div class="imager">
<div class="img" style="background-image: url(<?php echo $thumbnail; ?>);"></div>
</div>
<p class="ttl">
<?php echo get_the_title(); ?>
</p>
<p class="price"><?php echo the_field('a-price'); ?>円(税別)</p>
</a>
</li>
<?php endwhile;
$count = 4 - $count;
if($count > 0){
for( $i = 0; $i <= $count; $i++){echo '<li></li>';}} endif; ?>
</ul>
推荐阅读
- c++ - 函数参数中使用的复杂文字“i”
- visual-studio-2010 - 如何正确使用 EnableThemeDialogTexture()?
- javascript - 猫鼬,试图通过一个值找到一个对象
- powershell - 为什么 Powershell 在删除所有 Pssession 并添加一个新的之后不导入交换命令行开关?
- file-upload - 使用 JMeter 上传文件时遇到的问题(出现错误 - 无法开始导入 - 对象引用未设置为对象的实例)
- angular - Angular 站点使用时,带有参数的电子邮件超链接将变为小写(查询字符串)
- hive - 如何在 Hive 中爆炸地图数组
- android - 添加依赖项 com.google.android.material 后,Android Manifest Merger 失败
- python - 使用“for”或“if”条件在 Python 中创建 CSV 文件
- c# - 将 ASP.NET Webform 应用程序部署到 Windows 托管安全错误