Cool Hand Luke
Cool Hand Luke

Reputation: 2140

How to do a group by in the Wordpress?

I have a drivers post type which has a relationship called team. I want to group drivers by team so I can output them together in their groupings 'teams'. Hopefully that makes sense. I don't really understand the documentation I have a tried a few things but it seems to be missing details. This is what I have at the moment:

<?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;
?>

Here is my post type. Note the team relationship

Upvotes: 0

Views: 2195

Answers (1)

The Alpha
The Alpha

Reputation: 146239

You may try this

<?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
?>

If you want to get only one category (drivers) then

<?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;   
?>

May be this one can help you

<?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;  
}   
?>

Upvotes: 1

Related Questions