在 WordPress 搜索页显示搜索结果数量,可以通过修改搜索结果页面模板文件来实现。以下为你详细介绍具体步骤和实现方法。

1. 找到搜索结果页面模板文件


WordPress 通常使用search.php作为搜索结果页面的模板文件。如果你的主题中没有search.php文件,WordPress 会使用archive.php或者index.php来显示搜索结果。你可以在主题文件夹中查找并编辑相应的文件。

2. 添加代码显示搜索结果数量


在找到的模板文件中添加以下代码来显示搜索结果的数量。以下是几种不同位置和方式的添加示例。

示例一:在搜索结果标题附近显示


如果你希望在搜索结果标题附近显示搜索结果数量,可以在显示搜索结果标题的位置添加代码。例如,在search.php文件中找到类似下面的代码区域:
收起
php
<header class="page-header">
    <h1 class="page-title">
        <?php
        /* translators: %s: search query. */
        printf( esc_html__( '搜索结果:%s', 'your-theme-textdomain' ), '<span>' . get_search_query() . '</span>' );
        ?>
    </h1>
</header><!-- .page-header -->

在上述代码下方添加以下代码:
收起
php
<?php
global $wp_query;
$total_results = $wp_query->found_posts;
printf( esc_html__( '共找到 %d 个搜索结果', 'your-theme-textdomain' ), $total_results );
?>

完整的代码示例如下:
收起
php
<header class="page-header">
    <h1 class="page-title">
        <?php
        /* translators: %s: search query. */
        printf( esc_html__( '搜索结果:%s', 'your-theme-textdomain' ), '<span>' . get_search_query() . '</span>' );
        ?>
    </h1>
    <?php
    global $wp_query;
    $total_results = $wp_query->found_posts;
    printf( esc_html__( '共找到 %d 个搜索结果', 'your-theme-textdomain' ), $total_results );
    ?>
</header><!-- .page-header -->

代码解释:

 
  • global $wp_query;:引入全局的$wp_query对象,该对象包含了当前查询的相关信息。
  • $wp_query->found_posts:获取当前搜索查询所找到的文章总数。
  • printf函数:用于格式化输出文本,将搜索结果数量插入到相应的文本中。

示例二:在搜索结果列表开始位置显示


如果你希望在搜索结果列表开始的位置显示搜索结果数量,可以在循环显示搜索结果的代码之前添加上述代码。例如:
收起
php
<?php
global $wp_query;
$total_results = $wp_query->found_posts;
printf( esc_html__( '共找到 %d 个搜索结果', 'your-theme-textdomain' ), $total_results );
?>
<?php if ( have_posts() ) : ?>
    <div class="search-results-list">
        <?php
        while ( have_posts() ) :
            the_post();
            // 显示文章内容的代码
            get_template_part( 'template-parts/content', 'search' );
        endwhile;
        // 分页导航代码
        the_posts_navigation();
        ?>
    </div>
<?php else : ?>
    <p><?php esc_html_e( '未找到相关结果。', 'your-theme-textdomain' ); ?></p>
<?php endif; ?>

3. 保存并测试


完成代码添加后,保存模板文件。然后在 WordPress 网站的搜索框中输入关键词进行搜索,查看搜索结果页面是否正确显示了搜索结果的数量。
通过以上步骤,你就可以在 WordPress 搜索页显示搜索结果数量了。