2016-04-21 77 views
0

如何在页面上显示搜索结果之前将真实的“搜索结果计数”PHP - 在显示/计算“查询结果”之前,如何在页面上回显“查询结果计数”

<div><?php echo $search_result_count.' RESULTS'; ?></div> 

<div class="search-results"> 
    <?php if (have_posts()) while (have_posts()) : the_post(); ?> 
      <?php get_template_part('/include/pattern','listings'); ?>   
     <?php $search_result_count++ ?> 
    <?php endwhile; // end of the loop. ?> 
</div> 

<div><?php echo __('THERE ARE '.$search_result_count.' RESULTS'); ?></div> 

目前这个显示为...

0 RESULTS 

- LISTING #1 
- LISTING #2 
- LISTING #3 
- LISTING #4 

THERE ARE 4 RESULTS 

我想是这样的...

4 RESULTS 

- LISTING #1 
- LISTING #2 
- LISTING #3 
- LISTING #4 

THERE ARE 4 RESULTS 

必须有几个方法可以做到这一点.. 有任何想法吗? (你原来的代码之前)通过顶环

+2

好了,就可以不显示一个变量的值,你,你将值赋给它,您目前正在尝试做的.. –

+0

以前不可能,但可能是你可以通过使用jQuery或JavaScript来实现它。 – RJParikh

+0

只做两次循环。一旦进入顶层,只计算'$ search_result_count',然后再次显示结果。除非你在列表中有10,000个帖子,否则它不会是一个性能问题。 –

回答

-1

首先运行:

<?php 
$search_result_count = 0; 
if (have_posts()) : 
    while (have_posts()) : the_post(); 
     $search_result_count++; 
    endwhile; 
    rewind_posts(); // Resets the loop 
endif; 
?> 

.... your original code 

现在你可以使用你$search_result_count显示上岗。

除非有相当数量的帖子,否则不应该有任何性能问题(多于已经存在的情况,当你使用WordPress的时候,是的......我去了那里!)。

+0

对投票的评论? –

0

如果你使用PHP和MySQL,那么有一个非常简单的解决方案 - 使用mysqli_num_rows

示例代码 -

<?php 
$con=mysqli_connect("localhost","my_user","my_password","my_db"); 
// Check connection 
if (mysqli_connect_errno()) 
    { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; 

if ($result=mysqli_query($con,$sql)) 
    { 
    // Return the number of rows in result set 
    $rowcount=mysqli_num_rows($result); 
    printf("Result set has %d rows.\n",$rowcount); 
    // Free result set 
    mysqli_free_result($result); 
    } 

mysqli_close($con); 
?> 
+0

他使用Wordpress并且想要计算搜索结果。对数据库进行手动查询并不能真正帮助他。 –