Create / Close Div in Array

时间:2018-09-24 作者:DZ002720

发现了几个类似的问题,无法找到任何有效的方法。正在尝试设置从阵列数据创建的引导卡。如果数组有数据,我将使用下面的代码创建div。div开得很好,但关闭时遇到问题。下面的代码通常“起作用”,但数组的最后一项返回到外部。非常感谢您的帮助。

<?php $terms = get_the_terms( $post->ID , \'people\' );

$len = count($terms);
$i = 0;

foreach ( $terms as $term ) {

if ( $i == 0 ) {

    echo \'<div class="card-header text-white bg-success"> Team 
     </div>
     <div class="card">
      <ul class="list-group"> \'   ;
}

else if ( $i == $len - 1  ) {
    echo \'</ul>  </div>\' ;
}

$i ++ ;

echo \' <li class="list-group-item border-0"> 
            \' . $term->name . \' </li>  
     \';


}


?>
杰克·约翰逊的回答很完美。下面使用foreach循环实现相同的目标,可能会帮助其他人。。

<?php

$the_page = sanitize_post( $GLOBALS[\'wp_the_query\']->get_queried_object() );
$slug = $the_page->post_name;
$args = array(
\'post_type\' => \'research\',
\'posts_per_page\' => \'10\',
\'tax_query\' => array(
    array(
        \'taxonomy\' => \'researchcategory\',
        \'field\' => \'name\',
        \'terms\' => $the_page
        )
    )
);
$posts = new WP_Query( $args );
$posts = $posts->get_posts();

if (  $posts  && ! is_wp_error(  $posts ) ) { ?>

<div class="card mb-4 mt-4">
    <div class="card-header text-white bg-primary"> Research</div>
    <ul class="list-group">

        <?php
        foreach( $posts as $post ) { ?>
        <li class="list-group-item border-0">
            <?php echo esc_html( $term->name ) ?>

            <div class="title-meta">
                <?php add_filter( \'the_title\', \'max_title_length\'); ?>
                <?php echo \'<a href="\'.get_the_permalink().\'">  \'.get_the_title().\'  </a>\' ?>

                <div class="entry-meta">
                    <?php echo get_the_author(); ?> - <?php echo human_time_diff(get_the_time(\'U\'), current_time(\'timestamp\')).\'\'; ?>
                </div>

                <?php  } ;  ?>  </li> </ul>  </div>   <?php   } ; ?>

1 个回复
最合适的回答,由SO网友:Johansson 整理而成

您不需要计算或做所有事情来确定最后一个元素。检查函数的结果是否有效,输出DIV,然后在其中运行循环:

<?php

    // Get the terms
    $terms = get_the_terms( $post->ID, \'people\' );

    // Check if there\'s any results, and there\'s no error.
    // If so, output the opening and closing DIV and UL
    if ( $terms && ! is_wp_error( $terms ) ) { ?>

        <div class="card-header text-white bg-success">Team</div>

        <div class="card">
            <ul class="list-group">
                <?php
                    // Now time to output the terms themselves
                    foreach ( $terms as $term ) { ?>
                        <li class="list-group-item border-0">
                            <?php echo esc_html( $term->name ) ?>
                        </li><?php
                    }

                ?>
            </ul>
        </div><?php
    }

?>

结束