如果foreach循环中的if_array中没有相关的乘积,请关闭标题



如果数组中有匹配项,我想显示标题"Related Products",如果没有匹配项,则隐藏标题。我下面的代码显示了标题。如果没有产品,我该如何关闭它?

正如你所看到的,我已经注释掉了原始代码,我试图在查询中进行检查,但没有成功,否则我只能将标题放在if ($related_products->have_posts()){行下面。

<?php 
// Query products where product title matches a tag in the current article
$current_article_tags = wp_get_object_terms(get_the_ID(), 'knowledge_hub_tag', array('fields' => 'names'));
echo '<pre>'; print_r($current_article_tags); echo '</pre>';
$related_products = new WP_Query(array(
'posts_per_page' => -1,
'post_type'=> 'product',
/*'post_title' => array(
array(
//'taxonomy' => $current_article_tags,
'post_title' => 'varilite icon mid',
'operator'=> 'IN' //Or 'AND' or 'NOT IN'
),
)*/
));
//echo '<pre>'; print_r($related_products); echo '</pre>';
$products = $related_products->posts;
//echo '<pre>'; print_r($products); echo '</pre>';
if ($related_products->have_posts()){
echo '<h4>Related products</h4>';
foreach($products as $product) {
if(in_array($product->post_title, $current_article_tags, true)) {
echo '<p><a href="'.get_permalink( $product ).'">'.get_the_title($product).'</a></p>';
}
}
}


//wp_reset_postdata();
?>

试试这个。

<?php 
// Query products where product title matches a tag in the current article
$current_article_tags = wp_get_object_terms(get_the_ID(), 'knowledge_hub_tag', array('fields' => 'names'));
echo '<pre>'; print_r($current_article_tags); echo '</pre>';
$related_products = new WP_Query(array(
'posts_per_page' => -1,
'post_type'=> 'product',
/*'post_title' => array(
array(
//'taxonomy' => $current_article_tags,
'post_title' => 'varilite icon mid',
'operator'=> 'IN' //Or 'AND' or 'NOT IN'
),
)*/
));
//echo '<pre>'; print_r($related_products); echo '</pre>';
$products = $related_products->posts;
$show_title = false;
foreach($products as $product) {
if(in_array($product->post_title, $current_article_tags, true)) {
$show_title = true;
break;
}
}
if ($show_title){
echo '<h4>Related products</h4>';
foreach($products as $product) {
if(in_array($product->post_title, $current_article_tags, true)) {
echo '<p><a href="'.get_permalink( $product ).'">'.get_the_title($product).'</a></p>';
}
}
}
//wp_reset_postdata();
?>

只需检查数组是否有任何项。如果是,则只显示标题和产品。

最新更新