簡體   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