首页 > 解决方案 > 计算 PHP array_chunk 中的项目

问题描述

我有以下函数,它获取 wordpress 帖子并将它们输出到引导网格中(每行 3 个帖子)。每个数组块中有 3 个帖子。基本上我想要做的是如果块不完整并且只有2个帖子,那么该块中的第一个帖子会添加“col-sm-offset-2”类。我相信我需要一些方法来计算块中的帖子,但我不确定如何实现。

    function post_events($atts) {

    global $post;

    $args = array(
    'post_type'    => 'event',
    'post_status'  => 'publish',
    'orderby'      => 'date',
    'order'        => 'ASC',
    );

    $posts = get_posts($args);

    $posts_chunks = array_chunk($posts, 3);

    $output = '';

    foreach ($posts_chunks as $row) {

        $output .= '<div class="row">';

        foreach ($row as $post) {

            setup_postdata($post);

            $output .= '<div class="col-md-6 col-sm-6 event-item">';
            $output .= '<a href="' .get_the_permalink(). '">' .get_the_post_thumbnail(). '</a>';
            $output .= '<div class="event-item-text">';
            $output .= '<h3><a href="'.get_the_permalink(). '">' .get_the_title(). '</a></h3>';
            $output .= '<span class="event-date">' .get_the_date("d-m-Y"). '</span>';
            $output .= '<p>' .wp_trim_words( get_the_content(), 40, '...' ). '</p>';
            $output .= '</div>';
            $output .= '</div>';
        }

        $output .= '</div>';
    }

    return $output;
 }

add_shortcode('post_events','post_events');

标签: phparrayswordpress

解决方案


您可以只使用count()on $row,然后根据是否是第一次迭代来设置类:

$class = 'col-md-6 col-sm-6 event-item';
$count = count($row);

foreach( $row as $k => $post ) 
{
    $cls = ($k == 0 && $count < 2) ? $class.' col-sm-offset-2' : $class;
    setup_postdata($post);
    $output.= '<div class="'.$cls.'">';
    //...
}

推荐阅读