【问题标题】:How to do a group by in the Wordpress?如何在 Wordpress 中进行分组?
【发布时间】:2012-06-09 22:33:31
【问题描述】:

我有一个司机职位类型,其关系称为团队。我想按团队对驱动程序进行分组,以便我可以将它们一起输出到他们的分组“团队”中。希望这是有道理的。我不太了解我尝试过的文档,但似乎缺少细节。这是我目前拥有的:

<?php 
  $type = 'drivers';
  $args=array(
    'post_type' => $type,
    'post_status' => 'publish',
    'paged' => $paged,
    'posts_per_page' => 12,
    'ignore_sticky_posts'=> 0,
  );
  
$loop = new WP_Query( $args );
  

while ( $loop->have_posts() ) : $loop->the_post();

  get_template_part( 'team-driver' );
endwhile;
?>

这是我的帖子类型。

【问题讨论】:

    标签: mysql wordpress group-by custom-fields


    【解决方案1】:

    你可以试试这个

    <?php
    // get all the categories
    $cats = get_categories(); 
    // loop through the categries
    foreach ($cats as $cat)
    {
        // Get the cateogory ID
        $cat_id= $cat->term_id;
        //Header for the cateogry
        echo "<h2>".$cat->name."</h2>";
        // Make a custom wordpress query
        query_posts("cat=$cat_id&post_per_page=12");
        // start wordpress loop
        if (have_posts()) : while (have_posts()) : the_post(); 
    ?>
        <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
    <?php 
        echo '<hr/>'; 
        endwhile;
        endif; // End of WordPress loop
    } // End of foreach loop through category
    ?>
    

    如果您只想获得一个类别(驱动程序),那么

    <?php
    $cat_name = 'drivers';
    $term = get_term_by('name', $cat_name, 'category');
    $cat_id=$term->term_id;
    query_posts("cat=$cat_id&post_per_page=12");
    // start wordpress loop
    if (have_posts()) : while (have_posts()) : the_post(); 
    ?>
        <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
    <?php 
       echo '<hr/>'; 
       endwhile;
       endif;   
    ?>
    

    也许这个可以帮助你

    <?php
    $cat_names = array('team1', 'team2', 'team3');
    foreach($cat_names as $cat)
    {
        $term = get_term_by('name', $cat, 'category');
        $cat_id=$term->term_id;
        query_posts("cat=$cat_id&post_per_page=12");
        // start wordpress loop
        if (have_posts()) : while (have_posts()) : the_post(); 
    ?>
        <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
    <?php 
        echo '<hr/>'; 
        endwhile;
        endif;  
    }   
    ?>
    

    【讨论】:

    • 嗨,我需要的不是类别。我需要按我的团队分组,以便我可以输出:团队 1:来自团队 1 的司机 1,来自团队 1 的司机 2,然后团队 2:来自团队 2 的司机 1,来自团队 2 的司机 2。
    • 感谢您的帮助,但我很困惑。我没有使用类别,我使用的是帖子类型。我有帖子类型的驱动程序,并且我希望作为关系字段的团队字段对它们进行分组,因此我将驱动程序按团队分组,因为目前我可以将它们显示为一个团队,它们只是随机输出。我希望这是有道理的。
    • 我没有为此使用类别,所以它不起作用。您可以在我添加的图像中看到我的驱动程序帖子类型的自定义字段。如果我在我的团队帖子类型中创建一个与每个司机一对多的关系会更容易。基本上是先加入再成组,目前我是多对一的。
    猜你喜欢
    • 2018-12-10
    • 2015-03-23
    • 1970-01-01
    • 2018-11-03
    • 2021-03-10
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多