php - 计算 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');
解决方案
您可以只使用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.'">';
//...
}
推荐阅读
- c - 获取套接字的随机端口
- python-3.x - 如何避免movipy中打开文件过多的问题?
- h2o - H2O 隔离林——分数大于 1
- javascript - 为什么这个 React 功能组件不能显示存储在状态中的数组(通过 .map)?
- git - 如何知道我是否拥有对 Github Repo 的正确访问权限?
- docker - docker-compose 使用指定的网络名称运行
- neo4j - 深度汇总和关系
- powershell - Powershell:递归地将文件从源目录移动到上一级
- angular - 没有 ngOnDestroy,Angular 代码无法工作
- database - 如何解决错误 pgadmin4 错误 42p07?