我正在尝试构建我的分类法的字母索引。我正在拉这个词的第一个字母并在页面上显示它。但是,如果是新信,我只想显示第一个字母。这样我就可以将所有a组合在一起,然后组合b,等等。我以为我可以使用帖子计数,但它只适用于第一和第二篇文章。任何其他帖子都会输出第一个字母。非常感谢任何帮助,谢谢!
$post_type = 'book';
// Get all the taxonomies for this post type
$taxonomies = get_object_taxonomies( array( 'post_type' => $post_type )
);
foreach( $taxonomies as $taxonomy ) :
// Gets every "category" (term) in this taxonomy to get the respective
posts
$terms = get_terms( $taxonomy );
$count = 0;
foreach( $terms as $term ) :
$count++;
$current_letter = '';
if ($count == 1) :
$title_letter1 = strtoupper(substr($term->name,0,1));
if ($title_letter1 != $current_letter) {
echo "<h3>$title_letter1</h3>";
$current_letter = $title_letter1;
}
?>
<?php echo $term->name; ?>
<?php elseif ($count >= 2) :
$title_letter2 = strtoupper(substr($term->name,0,1));
if ($title_letter2 != $title_letter1 and $title_letter2 !=
$current_letter ) {
echo "<h2>$title_letter2 </h2>";
$current_letter = $title_letter2;
}?>
<?php echo $term->name; ?></div>
<?php else : ?>
<?php endif; ?>
答案 0 :(得分:0)
主要问题是您要为每个新字词重置$current_letter
,因此当您尝试在此行中检查时,您将丢失该值。您需要将它移到foreach循环之外 - 请参阅下面的代码。
其余代码可能正常工作,但特别是if ($title_letter2 != $title_letter1 and $title_letter2 != $current_letter )
条件检查很难说明。
只是编写代码的一个提示,以便更容易调试:基本上更少更好:-)因为它更容易更改并且更容易调试,因为出错的东西更少!
您可以简化代码以删除重复和不必要的变量,从而引入额外检查的需要:
foreach( $taxonomies as $taxonomy ) :
$terms = get_terms( $taxonomy );
$count = 0;
$current_letter = ''; // move this outside of the loop so you don't reset it every time
foreach( $terms as $term )
$count++;
// you need to do this regardless of the count, so just do it once here
$title_letter = strtoupper(substr($term->name,0,1));
if ($count == 1):
if ($title_letter != $current_letter)
echo "<h3>$title_letter</h3>";
elseif ($count >= 2):
if ($title_letter != $current_letter )
echo "<h2>$title_letter </h2>";
endif;
// you need to do this regardless of the count, so just do it once here
$current_letter = $title_letter;
echo $term->name;
endforeach;
endforeach;
备注:强>
if
语句在count&gt; = 2 count==1
和count >=2
下的代码完全正确
同样的事情,除了它是如何显示这封信。我希望这听起来并不像我批评你现有的代码,因为我不是,但我需要简化它只是为了看错了,而且更容易做到当需要更少的代码来做同样的事情时!
养成使用the DRY & KISS Software principles原则的习惯可能会帮助您(或我们!)解决您可能会发布的任何未来问题。
希望这会有所帮助:)