0 レビュー
2 回答
PHP、動的ループの周りにdivラップを追加
月ごとにグループ化されたイベントを出力するカレンダースクリプトに取り組んでいます。クロージングタグの問題がなければ、毎月divラッパーを追加する方法がわからないことを除いて、すべてが正常に機能しています。これが私のループコードです:
if ($posts) {
$month_titles = array();
$close = false;
foreach( $posts as $post ) {
setup_postdata( $post );
$month_title = date('F Y', strtotime(get_post_meta($post->ID,'_event_start_local', true)));
if(!in_array($month_title, $month_titles)) {
if($close) echo '</ul>';
echo '<h4>'.$month_title.'</h4>';
echo '<ul>';
$month_titles[] = $month_title;
$close = true;
}
echo '<li>'.get_the_title().'</li>';
}
if ($close) echo '</ul>';
}
これが現在の出力です:
<h4>Month Name 2018</ul>
<ul>
<li>Title of Event</li>
<li>Title of Event</li>
</ul>
次のようにしたいと思います:
<div>
<h4>Month Name 2018</h4>
<ul>
<li>Title of Event</li>
<li>Title of Event</li>
</ul>
</div>
divラップを追加するためにいくつかの異なる方法を試しましたが、閉じるのが早すぎるか遅すぎます。私はそれをあまりにも長い間いじっていたので、これに新鮮な目を向ける必要があります!
わからない
0
レビュー
答え :
解決策:
このロジックは、必要なものに対して機能するはずです:
// preset some vars
$oldMonth = null;
$firstItem = true;
foreach($posts as $post) {
setup_postdata($post);
$month_title = date('F Y', strtotime(get_post_meta($post->ID,'_event_start_local', true)));
// check if we have a new month coming up:
if($oldMonth != $month_title) {
// when it's the first one ever, just open the div
if($firstItem) {
echo "<div>";
$firstItem = false; //..and remember that the following aren't the first
} else { // else close the previous ones and open a new one
echo "</ul></div><div>";
}
// show the new month and open the list
echo '<h4>'.$month_title.'</h4>';
echo '<ul>';
}
echo '<li>'.get_the_title().'</li>';
$oldMonth = $month_title; // remember the last month
}
// at the end close the last ul and last div
echo '</ul></div>';
わからない
0
レビュー
答え :
解決策:
これらの行を変更しているようです:
if($close) echo '</ul>';
echo '<h4>'.$month_title.'</h4>';
から
if($close) echo '</ul></div>';
echo '<div><h4>'.$month_title.'</h4>';
あなたがやりたいことをするべきです。コード内の両方の場所で$close
のifを変更する必要があることに注意してください)
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。