0

好的,我有一个 foreach 语句在 wordpress 中的 3 个多站点博客中搜索关键字,如下所示:

<?php
 foreach ( $blogs as $blog ):
 switch_to_blog($blog['blog_id']);
 $search = new WP_Query($query_string);  
                     if ($search->found_posts>0) {
                            foreach ( $search->posts as $post ) {
echo "POST CONTEN";
                            }
                    }elseif ($search->found_posts===0) {
                        # code...
                        $notfound = true;
                    }
        endforeach;
if ($notfound) {
    # code...
    echo "POST NOT FOUND";
}

如果在所有 thre 博客中都没有使用该关键字的帖子,这会很好地响应 POST NOT FOUND 但如果博客 1 上有帖子但博客 2 或 3 上没有帖子,它仍然会回显 POST NOT FOUND 为什么?克里斯 // * ** * ****更新* ** * ** * ** * ** * ** * ** * ** * ** * ** * ** * **** /

<?php
 $searchfor = get_search_query(); // Get the search query for display in a headline
 $query_string=esc_attr($query_string); // Escaping search queries to eliminate potential MySQL-injections
 $blogs = get_blog_list( 0,'all' );
 $notfound = true;
 foreach ( $blogs as $blog ):
 switch_to_blog($blog['blog_id']);
 $search = new WP_Query($query_string);  
                     if ($search->found_posts>0) {
                         $notfound = false;
                    }
                    if($notfound){
                        ?>
                        <div class="post">
                                <h2><?php _e('Ingen resultater'); ?></h2>
                                <p><?php _e('Beklager, vi fant ingen innlegg som samsvarer med ditt søk: ' . get_search_query()); ?></p>
                            </div>
                        <?php
                    }else{
                         foreach ( $search->posts as $post ) {
echo "content";
                            }
                    }
        endforeach;

        ?>
4

2 回答 2

1

你的逻辑是倒退的。您应该从“未找到”条件开始,并在找到某些内容时将其更改为 false:

$not_found = true;

while ...
   if ($search->found_posts != 0) {
     $not_found = false;
   }
}
if ($not_found) {
  echo 'nothing found'; // $not_found is true
} else {
  echo 'found something'; // $not_found is false
}
于 2013-11-13T21:19:28.320 回答
-1

对不起格式。刚刚在这里复制了你的代码。做与你做的相反的事情,看看这里的变量 $found 。

<?php
 $found = false;
 foreach ( $blogs as $blog ):
 switch_to_blog($blog['blog_id']);
 $search = new WP_Query($query_string);  
                     if ($search->found_posts>0) {
                            foreach ( $search->posts as $post ) {
echo "POST CONTEN";
                            }
                      $found = true;
                    }elseif ($search->found_posts===0) {
                        # code...
                    }
        endforeach;
if ($found == false) {
    # code...
    echo "POST NOT FOUND";
}
于 2013-11-13T21:20:49.007 回答