期望的情况
我想在我的网站上创建所有使用类别的概述,按字母分组。然后我的下一步是对这些类别进行列化。
输出代码应如下所示:
<div class="list">
<ul>
<h3>A</h3>
<li>Alfa</li>
<li>Auto</li>
</ul>
<ul>
<h3>B</h3>
<li>Beta</li>
</ul>
</div>
或者:
<div class="list">
<ul>
<li>
<h3>A</h3>
<ul>
<li>Alfa</li>
<li>Auto</li>
</ul>
</li>
<li>
<h3>B</h3>
<ul>
<li>Beta</li>
</ul>
</li>
</ul>
</div>
现状
我现在的代码确实输出了一个列表,但输出如下:
<div class="list">
<ul>
<h3>A</h3>
<li>Alfa</li>
<li>Auto</li>
<h3>B</h3>
<li>Beta</li>
</ul>
</div>
因此,下面的代码只创建带有字母的列表,但没有分组。
$param_type = 'category__in'; // e.g. tag__in, category__in
$cat_args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_categories($cat_args);
if ($categories) {
$first_letter = null;
echo '<ul>';
foreach( $categories as $category ) {
$flag = 0;
if( $first_letter != substr( $category->name, 0, 1 ) ) {
$first_letter = substr( $category->name, 0, 1 );
$flag = 1;
}
if( $flag ) {
echo '<h3>'.$first_letter.'</h3>';
}
$args = array(
"$param_type" => $category->id,
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'ASC'
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . $category->name . '">' . $category->name . '</a></li>';
}
}
echo '</ul>';
}
wp_reset_query();
问题
有没有人可以帮助我将目前的情况发展到理想状态?
答案 0 :(得分:0)
我找到了解决方案。我不知道这是否是最佳方式,但无论如何它都有效。 任何建议或改进仍然是受欢迎的。
<?php
$param_type = 'category__in'; // e.g. tag__in, category__in
$args = array(
'orderby' => 'name',
'order' => 'ASC'
);
$categories = get_categories($args);
if ($categories) {
$first_letter = null;
$group_per_column = 2;
$i = 0;
$ic = 0;
foreach( $categories as $category ) {
$category_letter = strtoupper(substr($category->name,0,1));
if( $first_letter != $category_letter ) {
if ($i%$group_per_column == 0) {
if ($first_letter != '') echo '</ul></li></ul></div>' . $parent_ul;
$first_letter = $category_letter;
$i += 1;
$ic += 1;
echo "<div class=\"wrap column_$ic\"><ul class=\"category_list\"><li class=\"$category_letter\"><h2> - $i $category_letter - </h2>";
echo '<ul>';
} else {
if ($first_letter != '') echo '</ul></li></ul>' . $parent_ul;
$first_letter = $category_letter;
$i += 1;
echo "<ul class=\"category_list\"><li class=\"$category_letter\"><h2> - $i $category_letter - </h2>";
echo '<ul>';
}
}
$args = array(
"$param_type" => $category->id,
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'ASC'
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<li><a href="' . get_category_link( $category->term_id ) . '" title="' . $category->name . '">' . $category->name . '</a></li>';
}
}
echo '</ul></li></ul></div>';
}
wp_reset_query();
?>