I created a two loop into my WordPress page.
It should get the category name and should load all the child under the Category name.
Like this
____ Cat1 ______
product 1 product 2 product 3
____ Cat2 ______
product 1 product 2 product 3
So the thing is, while the products are looping, the Category name is also looping, so if I have 3 products under the cat name i will have 3 cat name as well.
Here is my code:
<div class="pr_grid_cell clearfix">
<?php
//for each category, show posts
$categories=get_categories();
foreach($categories as $cat) {
$args=array(
'post_type' => 'products',
'showposts' => -1,
'category__in' => array($cat->term_id)
);
$posts=get_posts($args);
if ($posts) { ?>
<div class="pr_grid buy-online">
<span class="hcenter">
<h5><?= $cat->name ?></h5>
<? foreach($posts as $post) {
setup_postdata($post); ?>
<? if( get_field('buy_online_href') ): ?>
<?php // create our link now that the post is setup ?>
<span class="pr_img_href" href="<? the_permalink(); ?>">
<img class="ii" src="<?php the_field('product_thumbnail'); ?>">
<a class="button" target="_blank" href="<?php the_field('buy_online_href'); ?>">Buy Online</a>
<a class="button" target="_blank" href="/store-locator">Find Near you</a>
</span>
<? endif ?>
<?php
} // foreach($posts
} // if ($posts
} // foreach($categories
?>
</span>
</div>
</div>
Could you guys please look into my code and correct me?
Any help would be appreciated.
<?php
openings. 2) Clean up the indenting of your code so it's readable. This in fact may show you where your look is going wrong. 3)query_posts()
is evil! Don't use it! Usepre_get_posts
orWP_Query
instead. Google all three to learn the differences. 4) This may be your issue, but I don't see anyendforeach
for yourforeach
loop.: endforeach
and: endif
etc. with proper curly brackets{}
, then with an IDE one will be able to quickly look at your code to see if there's something missing.}
/closing bracket at the end. I saw a bunch of missing;
/semicolons and as @mrwweb already suggested, you are destroying & overwriting the main query with yourquery_posts()
once per loop. Do you have debugging enabled (see Codex about that)? And do you have short PHP tags on your server enabled? Update your question (instead of commenting) with your answers. And please: Fix intending your code. That is highly unreadable that way.query_posts