0

I want to count the custom fields and give the columns the right width to work with Bootstrap 3.

If there are 2 entries I want it to be:

<div class="col-md-6">

If there are 3 entries I want it to be:

<div class="col-md-4">

But it just puts the count number in each div.

EDIT: The solution of "num8er" helped me a lot, THX again! If someone finds this - this is how it works with a normal wordpress loop:

<?php 
if ( have_posts() ): ?> 

<?php $elements = []; 
while ( have_posts() ): the_post(); 
$element = get_the_title(); 
$elements[] = $element;
endwhile; 

if(sizeof($elements)>0) {
    $size = ceil(12 / sizeof($elements));
    if($columns<2) $columns = 2;
        foreach($elements AS $element) {
              echo '<div class="col-md-'.$size.'">'.$element.'</div>';
        }
    }

endif; 
?>

E. g. this is the DOM if i have 6 articles:

<div class="col-md-2"><h2>Homer Simpson’s  Guide  to  Tom Cruise</h2></div>
<div class="col-md-2"><h2>Homer Simpson’s  Guide  to  Tom Cruise</h2></div> 
...
1
  • 1
    You have to know the number of post ahead and then decide how many columns you need. If there are 3 posts your code will produce 4 columns col-md-12, col-md-6, col-md-4 and col-md-3 because you increase counter inside the loop. Commented Jun 17, 2015 at 12:38

1 Answer 1

2

let's collect the output to array $elements and get the size of column and wrap with it:

<?php if( have_rows('buehne_inhalt', 'option') ): ?>

  <h2><?=the_sub_field('subline')?></h2>
  <div class="row">
  <$php 
  $elements = []; 
  while( have_rows('buehne_inhalt', 'option') ): the_row();
    $image = get_sub_field('buehne_bild');
    $size = 'img-s';
    if( $image ) {
        $element = wp_get_attachment_image( $image, $size );
    }

    $elements[] = $element;
  endwhile; 

  if(sizeof($elements)>0) {
    $size = ceil(12 / sizeof($elements));
    if($columns<2) $columns = 2;

    foreach($elements AS $element) {
      echo '<div class="col-md-'.$size.'">'.$element.'</div>';
    }
  }
  ?>
</div>
<?php endif; ?> 
Sign up to request clarification or add additional context in comments.

1 Comment

If i use this code the "subline" is outside of the <H2> element (before the DIVs).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.