Home › Forums › ACF PRO › How to style dynamic data from a relationship ACF field into a two column grid
I’ve create a website that has Home Listings and Communities. I create a two way Relationship field and used the two way plugin to help me associate the data. That part worked great, except the following code renders a single column and the data just stacks one after the other vertically. I have exhausted this for hours trying to figure out how to get the dynamic data that is being queried to responsively flow into two columns. Here’s my “foreach” PHP code. want the images be two column NOT one column stacked. HOW? They are dynamic from the database so I cannot add columns in the html since they are dynamically generated.
HELP!
Here’s my code:
<?php $homelistings = get_field('choose_home_listing');?>
<?php foreach($homelistings as $homelisting):?>
<div class="home-listing-row">
<div class="home-listing-column">
<img class="home-listing-img" src="<?php echo get_the_post_thumbnail_url($homelisting->ID,'full');?>">
<h5 class="home-listing-post-title">The <?php echo $homelisting->post_title;?></h5>
</div>
</div>
<?php endforeach;?>
@whynotadv from what I can gauge, you want it to render more like a grid (2 columns per row) and continuously create new rows after each 2 listings?
OPTION A:
CSS Grid would play perfectly. You can set columns to split evenly in width (grid-template-columns: 1fr 1fr), and after each 2 items css grid would break to a new row automatically for you. Depending on existing styles and so forth, it will take a bit more in CSS, but definitely achievable and pretty straight forward with CSS Grid Layout knowledge.
Which can then be adjusted for mobile responsive when needed. Say when you hit iPad, you can change to grid-template-columns: 1fr (instead of 2 1frs) and now it changes back to a single item per row without having to change any HTML
The other cool thing here is that it can then be configured to have all rows with equal height or they could vary. Up to you.
OPTION B:
You can hack a bit by using a counter in PHP and conditionally add in container stuff after each 2 items, but CSS Grid is way better and so much more flexible.
CSS Grid worked great for me and then I tweaked the wrapper and inner container from there, it was really convenient.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.