John Davidson

php - Wordpress - Split custom posts into rows and columns

0 comments
Message:


I have a layout where we want to place the custom posts types on alternating rows and 2 & 3 columns.


so basically:


<div class="wrapper">
<div class="row">
<div>post 1</div>
<div>post 2</div>
</div>
<div class="row">
<div>post 3</div>
<div>post 4</div>
<div>post 5</div>
</div>
<!-- then 2 new row with 2 columns followed by 3 columns and so on -->
</div>

Any suggestions?



My Answer:
columns. Here's how you can achieve this in WordPress using PHP:

1. First, you need to query the custom post types using WP_Query. You can specify the post type and any other parameters you need in the query.

php
$args = array(
'post_type' => 'your_custom_post_type',
'posts_per_page' => -1, // Get all posts
);

$custom_query = new WP_Query($args);


2. Next, you can loop through the custom posts and output them in alternating rows and 2 columns.

php
if ($custom_query->have_posts()) {
$count = 0;
while ($custom_query->have_posts()) {
$custom_query->the_post();

if ($count % 2 == 0) {
echo '
';
}

echo '
';
// Output your custom post content here
the_title();
the_content();
echo '
';

if ($count % 2 != 0) {
echo '
'; // Close row
}

$count++;
}

if ($count % 2 != 0) {
echo '
'; // Close row if there are odd number of posts
}
}

wp_reset_postdata();


3. Finally, you can style the rows and columns using CSS to achieve the desired layout.

css
.row {
display: flex;
flex-wrap: wrap;
}

.col-md-6 {
width: 50%;
padding: 10px;
box-sizing: border-box;
}


This code will output the custom posts in alternating rows and 2 columns. You can customize the layout further by adding additional CSS styles or modifying the PHP code as needed.

Rate this post

3 of 5 based on 3526 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us