Создать/Закрыть Div в массиве [закрыто]
Нашел несколько похожих вопросов, не смог заставь что-нибудь работать. Попытка настроить загрузочную карту, созданную на основе данных массива. Я использую приведенный ниже код для создания divs, если в массиве есть данные. 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
1 answers
Вам не нужно считать или делать все необходимое, чтобы определить последний элемент. Проверьте, является ли результат функции допустимым, выведите 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
}
?>
0
Author: Jack Johansson, 2018-09-24 02:19:33