【问题标题】:Generating Bootstrap Columns with PHP使用 PHP 生成引导列
【发布时间】:2015-10-25 01:48:46
【问题描述】:

我正在尝试使用高级自定义字段为 Wordpress 主题制作一些引导布局。我现在已经设置好了,所以如果你有 2 个内容字段,它会生成一个“6”宽的列。如果您有 3 个字段,则会生成一个“4”字段列。

<?php if(get_field('link_tiles')) : 

while (has_sub_field('link_tiles')) :

$number_of_cols = count(get_field( 'link_tiles' ));

if ($number_of_cols == 2) {
         echo '<div class="col-md-6" style="padding: 0; margin: 0;">';
       }
       elseif ($number_of_cols >= 3) {
         echo '<div class="col-md-4" style="padding: 0; margin: 0;">';
       }
?>

我现在真正想要的是,如果你输入了 4 个字段,它会生成 3x“4”宽度的列,然后生成 1x“6”宽度的列,然后如果你输入了 6 个字段,它会返回生成“4”个宽度的列。我想使用 While 循环需要一些逻辑,但我不太清楚它的逻辑。我对 PHP 很陌生,任何帮助将不胜感激!

【问题讨论】:

    标签: php wordpress twitter-bootstrap advanced-custom-fields


    【解决方案1】:

    很难说没有看到周围的代码,但您必须已经在遍历列(每个列都回显&lt;div&gt;)。你在遍历一个数组吗?是否已经为当前索引设置了变量?

    如果是这样,逻辑可能是这样的,假设 $index 等于当前列号:

    // set default for two columns
    $col_class = 'col-md-6';
    
    if ($number_of_cols == 3) {
      $col_class = 'col-md-4';
    } elseif ($number_of_cols == 4 && $index < 4) {
      $col_class = 'col-md-4';
    } elseif ($number_of_cols == 4 && $index == 4) {
      $col_class = 'col-md-6';
    }
    
    echo '<div class="' . $col_class . '">';
    

    虽然看起来如果您有 4 列,但您确实需要 .col-md-3 的 4 列,而不是上面指定的 .col-md-4 的 3 列和 .col-md-6 的一列(总共 18 列;引导行最多为 12 列)。

    更新:

    这有点伪代码,但希望能给你一些关于如何继续的想法。请注意,显然您仍然需要为每一列输出内容。

    <?php if(get_field('link_tiles')) :
    
        $number_of_cols = count(get_field( 'link_tiles' ));
        $counter = 1;
    
        while (has_sub_field('link_tiles')) : 
            // set default for two columns
            $col_class = 'col-md-6';
    
            if ($number_of_cols == 3) {
              $col_class = 'col-md-4';
            } elseif ($number_of_cols == 4 && $counter < 4) {
              $col_class = 'col-md-4';
            } elseif ($number_of_cols == 4 && $counter == 4) {
              $col_class = 'col-md-6';
            }
    
            echo '<div class="' . $col_class . '"></div>';
    
            // increment the counter for the next column
            $counter++;
    
        endwhile;
    
    endif; ?>
    

    【讨论】:

    • 我正在使用高级自定义字段重复器字段插件,因此我为每个字段添加了一个新列。我会更新第一篇文章。
    • 那么您使用的是此处列出的基本循环之类的东西吗? advancedcustomfields.com/resources/repeater
    • 没错,没错。它计算创建的字段行数。
    • 谢谢 Benjarwar,这正是我所追求的!
    猜你喜欢
    • 1970-01-01
    • 2015-10-20
    • 2018-01-05
    • 2012-12-16
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多