首页 > 解决方案 > 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'); ?>円(税別)&lt;/p>
        </a>
    </li>
    <?php endwhile; ?>
</ul>
<?php endif; ?>

标签: phpwordpress

解决方案


你可以检查帖子数

<?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'); ?>円(税別)&lt;/p>
            </a>
        </li>
        <?php endwhile;
        $count = 4 - $count;
        if($count > 0){
           for( $i = 0; $i <= $count; $i++){echo '<li></li>';}} endif; ?>
    </ul>

推荐阅读