2017-09-04 89 views
0

我试图建立我的分类的字母索引只显示。我正在拉该字词的第一个字母并将其显示在页面上。但是,如果它是一个新的字母,我只希望显示第一个字母。这样我可以将所有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

下面的答案适用于您,或者您需要更多的帮助吗? – FluffyKitten

回答

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; 

注:

  • 也无需为2个独立的变量信 - 事实上, 包括第二个变量意味着你必须在 在计数> = 2
  • 添加额外的检查你的 if声明点
  • 它也是很好的做法不重复你在做什么(其称为 的DRY原则编程 - 不要重复自己)。对于 例如,count==1count >=2下的代码做正是 同样的事情,除了它是如何显示的字母。

我希望这听起来并不像我批评你现有的代码,因为我不是,但我需要简化它只是为了看看什么是错的,而且是很很容易做时,有更少的代码需要做同样的事情!

获取使用the DRY & KISS Software principles原则的习惯可以帮助你(或我们)与故障排除可能会发布任何未来的问题。

希望这会有所帮助:)

相关问题