繁体   English   中英

计算PHP array_chunk中的项目

[英]Counting items in a 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');

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

$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.'">';
    //...
}

由于已分块,因此子数组将基于0 ,而第一篇文章将为0 因此,只需检查一下,如果count小于3

foreach ($posts_chunks as $row) {

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

    foreach ($row as $key => $post) {
        $extra = '';  //set extra class to empty
        if($key == 0 && count($row) < 3) { //check first post and count less than 3
            $extra = 'col-sm-offset-2 '; //set extra class
        }
        setup_postdata($post);
        //use $extra somewhere
        $output .= '<div class="'.$extra.'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>';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM