This is my current loop to display my products via woocommerce. When I do print_r($category_array); It returns the array, but when I try to use a function to call it so I can do what I want to with the data, it makes and my entire screen doesn’t display after the loop. Maybe it’s a mistake in my function? Still very new to woocommerce and wp_loops. Thank you
<?php
// WP_Query arguments
$args = array(
'p' => 'product',
'post_type' => array( 'product' ),
'order' => 'ASC',
'post_per_page' => 20,
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
function filter_categories($categories) {
foreach ($categories as $category) {
echo $category->name;
}
}
?>
<div class="row">
<div class="col-2">
<?php echo the_post_thumbnail(get_the_ID(), 'thumbnail'); ?>
</div>
<div class="col-7">
<a href="<?= get_permalink(); ?>"><?= the_title()?></a>
<br/>
<?php
$category_array = get_the_terms(get_the_ID(), 'product_cat');
filter_categories($category_array);
?>
</div>
<div class="col-3 text-right ">Price</div>
</div>
<?php
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
?>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The problem is here:
while ( $query->have_posts() ) {
$query->the_post();
function filter_categories($categories) {
foreach ($categories as $category) {
echo $category->name;
}
}
You shouldn’t declare a function inside a loop. Every time it loops around the filter_categories function gets declared again, but named functions can only be declared once, so it crashes the second time round, and everything stops.
If you look in your PHP error log, you should see an error message about redeclaring filter_categories confirming this.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0