首页 > 解决方案 > PHP Wordpress 循环导致卡片在卡片内部而不是单独呈现

问题描述

我在 wordpress 主页上有一个简单的循环,其中包含 3 篇随机文章。它间歇性地将卡片呈现在其他卡片中,而不是 3 张单独的卡片。我觉得这是随机拉入它们引起的时间问题。有没有办法强制它们分别渲染?

<div class="row">
    <?php 
        $args = array(
            'post_type' => 'post',
            'orderby'   => 'rand',
            'posts_per_page' => '3'
        );

        $loop = new WP_Query($args); ?>
        
    <?php if ( $loop->have_posts() ) : ?>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <div class="card" data-url="<?php echo the_permalink(); ?>">
                <div class="card-body">
                    <?php the_post_thumbnail('homepage-thumbs', array( 'class' => 'aligncenter' )); ?>
                    <h3><a href="<?php echo the_permalink(); ?>"><?php the_title(); ?></a></h3>
                    <span><i class="fal fa-user"></i> by <?php the_author(); ?></span>
                    <p></p>
                    <p><?php echo substr(get_the_content(), 0, 128); ?>...</p>  
                </div>
            </div>
        <?php endwhile; ?>
    <?php endif; ?>
</div>

标签: phpwordpress

解决方案


您的代码在我的测试中有效。但是,我会使用wp_trim_words来创建您的摘录,而不是您所做的,这可能会在中间剪掉一个单词。

<div class="row">
    <?php 
        $args = array(
            'post_type' => 'post',
            'orderby'   => 'rand',
            'posts_per_page' => '3'
        );

        $loop = new WP_Query($args); ?>
        
    <?php if ( $loop->have_posts() ) : ?>
        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
            <div class="card" data-url="<?php echo the_permalink(); ?>">
                <div class="card-body">
                    <?php the_post_thumbnail('homepage-thumbs', array( 'class' => 'aligncenter' )); ?>
                    <h3><a href="<?php echo the_permalink(); ?>"><?php the_title(); ?></a></h3>
                    <span><i class="fal fa-user"></i> by <?php the_author(); ?></span>
                    <p></p>
                    <p><?php 
                        $theContent = get_the_content();
                        // strip out any shortcodes from the excerpt
                        $theContent = strip_shortcodes( $theContent );
                        // wp_trim_words($content, number_of_words, read_more_text)
                        echo wp_trim_words( $theContent, 30 , '...' );?></p>  
                </div>
            </div>
        <?php endwhile; ?>
    <?php endif; ?>
</div>

推荐阅读