Home > Enterprise >  How show 2 categories in 1 loop, PHP(WordPress)
How show 2 categories in 1 loop, PHP(WordPress)

Time:06-03

I would like to show like below in HTML with PHP.

It assumes there are six categories.

<div class='box'><p>category 1</p><p>category2</p></div>
<div class='box'><p>category 3</p><p>category 4</p></div>
<div class='box'><p>category 5</p><p>category 6</p></div>

However, I don't know how I do it with PHP. I did below, but it shows only category 1&2.

<?php $categories = get_categories();foreach ($categories as $category):?>
            <div ><!-- genre 1 -->
                <div >
                </div>
                <div >
                <?php $categories = get_categories(); $x=1; $num=3; foreach ($categories as $category): ?>
                <?php if( $x>=$num ) { break; } else { ?>
                    <div >
                        <a href="<?php echo esc_url(get_category_link($category->term_id)); ?>" >
                            <img src="<?php echo z_taxonomy_image_url($category->term_id); ?>" alt="本">
                        </a>
                        <a href="<?php echo esc_url(get_category_link($category->term_id)); ?>" >
                            <p><?php echo $category->name; ?></p>
                        </a>
                    </div>
                <?php } $x   ; ?>
                <?php endforeach; ?>
                </div>
                <div >
                    <p>ジャンルメニュー</p>
                </div>
            </div><!-- genre 1 -->
            <?php endforeach; ?>

Please teach me how it works I want.

CodePudding user response:

You can follow the example below. 

$categories = array("category1", "category2", "category3", "category4");
foreach (array_chunk($categories, 2) as $chunk) {
    echo "<li>" . implode(', ', $chunk) . "</li>\n";
}

This will output the two value side by side. Array_chunk is a php function that splits an array into chunks, once you get that result you can output it any way, here for example using lists but you can change it to paragraphs.

https://www.php.net/manual/en/function.array-chunk.php

CodePudding user response:

You can use array_chunk to split an array into different groups & run your loop on this group to make it work.

foreach (array_chunk(get_categories();, 2) as $group) {
    //render item
    foreach ($group as $item) {
       <div class='box'><p>$item[0]->name</p><p>$item[1]->name</p></div>
    }

}
  • Related