如果 foreach 循环内的 if_array 中没有相关产品,则关闭标题

问题描述

如果数组中有匹配项,我想显示标题“相关产品”,如果不匹配则隐藏标题。不管怎样,我下面的代码显示标题。如果没有产品,我如何关闭它?

如您所见,我已经注释掉了我尝试在查询中进行检查的原始代码,但没有成功,否则我可以将标题放在 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,true)) {
            echo '<p><a href="'.get_permalink( $product ).'">'.get_the_title($product).'</a></p>';
        }
    }

}
//wp_reset_postdata();
?>

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