How would the code below (which is in a foreach loop) sometimes return something and sometimes return nothing when passed the same variables:
$term_id = 76;
$term_parent = 75;
if($term_id != 114 && $term_id != 115 && $term_parent != 83){
$term_link_content = 'something';
} else {
$term_link_content = 'nothing';
}
-- Based on responses so far, the full code is below. I'm basically after the first term that isn't equal to any of the ids listed. And I've checked the loop by outputting the $term_id and $term_parent for different posts which have the same terms so I can see that the if statement is being passed the same values but sometimes the $term_link_content variable has content and other times it's empty.
$posts = get_posts('post_type=products&product_categories=Best Sellers');
fore开发者_如何学Goach($posts as $post){
$post_ID = $post->ID;
$terms = get_the_terms( $post_ID, "product_categories" );
$i = 0;
foreach($terms as $term){
$term_id = $term->term_id;
$term_parent = $term->parent;
$term_name = $term->name;
$term_slug = $term->slug;
if($term_id != 114 && $term_id != 115 && $term_parent != 83){
// only get the first
if(++$i > 1) break;
$term_text = $term_name;
$term_link = $url.'/shop/'.$term_slug;
$term_link_content = '<span class="term_text"><a class="'.$card_colour.'" href="'.$term_link.'">'.$term_text.'</a></span>';
} else { $term_link_content = ''; }
}
}
I presume you define $term_id
and / or $term_parent
before entering your foreach
loop, and perform the rest of the code in the body of the loop.
However, when you do something like this:
foreach (getTerms() as $term) {
// perform an if-statement
}
This might change the variables you defined, eg.:
function getTerms() {
global $term_id, $term_parent;
// probably some database-connection that changes $term_id and $term_parent.
}
Correct me if I'm wrong, but I'm pretty sure Wordpress's functions work this way, so you shouldn't trust generic global variables when you're using Wordpress, when you're developing plugins or when you're using functional-oriented (instead of object-oriented) framework.
精彩评论