I was trying to get some posts from a Custom Post Type "dish" with a value of ACF as the price. I am trying to show the name of the dishes with the price and came up with this code. I want to know if the loop part in this code is considered good practice?
<div id="main-content">
<div class="container-lg overflow-hidden">
<div class="row gx-5 d-flex flex-wrap">
<?php
$categories = get_categories();
foreach ($categories as $category){
$categoryName = $category->name; // look into the object named $category and then look into the variable named "name"
if ($categoryName != "Uncategorized"){
?>
<div class="p-4 col-6">
<div>
<h3><?php echo $categoryName;?></h3>
</div>
<?php
$args = array(
'posts_per_page' => -1,
'post_type' => "dish",
'category_name' => $categoryName
);
$dishes = get_posts($args);
foreach ($dishes as $dish){
?>
<div>
<span><?php echo $dish->post_title; ?></span>
<span class="float-end"><?php echo the_field('price', $dish); ?></span>
</div>
<?php
}
?>
</div>
<?php
}
}
?>
</div>
</div>
</div>
I didn't use the have_posts()
loop as I thought all post would be called for each category. So I am not sure now if the code I used is a good practice on the archive page. The other way I saw was to custom query for each category. But again I wasn't sure if Custom query inside a loop would be a good idea in case there were thousands of post. Please advise.
Short answer:
Yes it's fine. I'd use the same approach every time. Avoid writing your own custom sql query whenever you can. The combination of get_posts
and category_name
works just fine.
Not sure if this a typo or not, but i'd also replace:
<span class="float-end"><?php echo the_field('price', $dish); ?></span>
with
<span class="float-end"><?php echo the_field('price', $dish->ID); ?></span>