Jump to content

Help - 2 Variables in foreach loop


MYGM

Recommended Posts

Hello, I have been trying to figure out how to write a certain php query and for the life of me I can not figure it out. I've tried searching on google like a mad man and still can not figure it out. Maybe Im missing something, Im not sure. I came across this site while googlin for answers.  The php code is for a wordpress site I am working on. 

 

 

Here is my current code -

<?php
$custom_terms = get_terms('videoscategory');
$other_custom_terms = get_terms('product_category');

foreach(array($custom_terms as $custom_term) {
wp_reset_query();
$args = array('post_type' => 'product',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'videoscategory',
'field' => 'slug',
'terms' => $custom_term->slug
),
array(
'taxonomy' => 'product_category',
'field' => 'slug',
'terms' => $other_custom_term->slug
),

)

);

$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h1 style="margin-top:10px;">'.$custom_term->name.'</h1>';

while($loop->have_posts()) : $loop->the_post();
echo '<h2><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
endwhile;
}
} ?>
 

Im trying to list all the posts that are in both of my custom taxonomies, however when I try using the code nothing shows but when I use 1 taxonomy at a time, with one array, it works perfectly.  Someone on gave me some advice but I do not understand it - generate array of your second taxonomy terms and feed it into the query - What exactly is that advice telling me to do? Any help is appreciated. Thanks.

Link to comment
https://forums.phpfreaks.com/topic/276702-help-2-variables-in-foreach-loop/
Share on other sites

Ok I figured it out. Just incase anyones interested, here's the code-- 

<?php
$custom_terms = get_terms('your_other_category');
$other_custom_terms = get_terms('your_category');

foreach ($custom_terms as $custom_term) {
foreach ($other_custom_terms as $other_custom_term) {
wp_reset_query();
$args = array('post_type' => 'product',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'your_category',
'field' => 'slug',
'terms' => $other_custom_term->slug
),
array(
'taxonomy' => 'your_other_category',
'field' => 'slug',
'terms' => $custom_term->slug,
),
),
);

$loop = new WP_Query($args);
if($loop->have_posts()) {
echo '<h1 style="margin-top:10px;">'.$custom_term->name.'</h1>';

while($loop->have_posts()) : $loop->the_post();
echo '<h2><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
endwhile;
}
}
} ?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.