I have a carousel which has to display two items per column in each item. I tried using foreach method and array_chunk() to do so, but it doesn’t seem to do the work.
This is the code I am working with:
<div class="section cataloge">
<div class="section-wrapper">
<div class="container">
<div class="cataloge-page">
<?php
if ($cataloge->have_posts()) {
?>
<div class="cataloge-slider owl-carousel owl-theme">
<?php
while ($cataloge->have_posts()) {
$cataloge->the_post();
$input_array = array($cataloge);
foreach (array_chunk($input_array, 2, true) as $column) {
?>
<div class="cataloge-slider-item-wrapper">
<?php
foreach ($column as $input_array) {
?>
<article class="cataloge-item">
<figure class="cataloge-item-img img-placeholder">
<?php the_post_thumbnail(); ?>
<?php
if (!empty(get_field('sticky_text'))) {
?>
<div class="cataloge-sticky"><?php the_field('sticky_text'); ?></div>
<?php
}
?>
</figure>
<div class="cataloge-item-data">
<h4 class="cataloge-item-title"><?php the_title(); ?></h4>
<div class="cataloge-item-category">
<?php
if (have_rows('cataloge_category')) {
while (have_rows('cataloge_category')) {
the_row();
?>
<?php
if (!empty(get_sub_field('cataloge_category_item'))) {
?>
<span><?php the_sub_field('cataloge_category_item'); ?></span>
<?php
}
?>
<?php
}
}
?>
</div>
<div class="cataloge-item-info"><?php the_content(); ?></div>
<div class="cataloge-item-action">
<?php
if (!empty(get_field('cataloge_file'))) {
?>
<a href="<?php the_field('cataloge_file'); ?>">
<svg width='25' height='25'>
<use xlink:href='<?php echo get_template_directory_uri(); ?>/frontend/fontawesome/solid.svg#eye'></use>
</svg>
</a>
<?php
}
?>
<?php
if (!empty(get_field('cataloge_download_file'))) {
?>
<a href="<?php the_field('cataloge_download_file'); ?>" download="">
<svg width='25' height='25'>
<use xlink:href='<?php echo get_template_directory_uri(); ?>/frontend/fontawesome/solid.svg#download'></use>
</svg>
</a>
<?php
}
?>
</div>
</div>
</article>
<?php
}
?>
</div>
<?php
}
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
What is it that I’m missing? Is there another way, other than foreach or/and array_chunk to get the result?
2
Answers
You can debug by
echo
orprint_r
step by step.I think problem here
$input_array = array($cataloge);
Change to
$input_array = (array) $cataloge;
There’s quite a few problems that you’re going to run into doing it this way. To address the main problem, you’re using array_chunk on the entire query object, not just the posts. This might be why it’s not working as expected. You would probably want to do
array_chunk($cataloge->posts)
to chunk them.However you’ve put this loop in a loop of all your posts, which means each iteration of that loop will repeat this. So if you have 10 posts in your $cataloge query, you’ll end up with 50 slides, with 45 of them being duplicates. If we instead use a foreach loop with the array_chunk outside of the while loop (remembering to use setup_postdata()) we should be more on the right track: