I’ve been stuck on this issue all day, and I just keep getting nowhere with it, hoping someone can help!
I’m building a site for a restaurant that has multiple locations and need to list out each drink that exists at each specific location. These drinks need to then be sorted by category (brown, white, tomato, beer, wine). I feel like I’m extremely close to a solution, but I’ve been banging my head for the last while.
Here’s my code:
$drinks = get_posts('post_type=drinks&numberposts=-1');
$show_brown_title = false;
$show_white_title = false;
$show_tomato_title = false;
$show_wine_title = false;
$show_beer_title = false;
if ( $drinks ) {
foreach( $drinks as $drink ) {
$id = $drink->ID;
$drink_location = $drink->drink_location;
if($drink->drink_category == 'Brown' && $drink_location && in_array($site_slug, $drink_location)) {
if($show_brown_title == false) {
echo '<h4><span>Brown</span> Cocktails</h4>';
echo '<ul>';
$show_brown_title = true;
}
echo '<li>';
echo '<span class="drink_title">'.$drink->post_title.'</span>';
echo '<span class="drink_ingredients">'.$drink->drink_ingredients.'</span>';
echo '<span class="drink_price">'.$drink->price_oz.'</span>';
echo '</li>';
}
if($drink->drink_category == 'White' && $drink_location && in_array($site_slug, $drink_location)) {
if($show_white_title == false) {
echo '<h4><span>White</span> Cocktails</h4>';
echo '<ul>';
$show_white_title = true;
}
echo '<li>';
echo '<span class="drink_title">'.$drink->post_title.'</span>';
echo '<span class="drink_ingredients">'.$drink->drink_ingredients.'</span>';
echo '<span class="drink_price">'.$drink->price_oz.'</span>';
echo '</li>';
}
}
}
For the most part, this works. However, I’m running into 2 issues.
- I can’t figure out how to close the unordered list after I’m done with each category.
- This groups by category for the most part, however, if I have a drink that comes later, it will not actually put it into the right category, it’ll just go into whatever category is at the bottom. I’m not sure if this is because I’m not closing the unordered list, or if because of the order that the posts are being pulled from WP.
Let me know if I’m explaining this alright, and I really appreciate any help you guys can offer!
Z
Bellow is my solution.
Note: get_posts uses the orderby parameter to order the posts by drink_category.
The code is simplified to only start
<ul>when drink_category changes and to end</ul>on category change too. Code also checks that html to output has been assigned a value and appends to it a final</ul>in case one is not appended already.