首页 视频课程 主题开发课程第02章、开发实例 WordPress入门实例:搜索结果页制件方法

WordPress入门实例:搜索结果页制件方法

2023-06-11 / 506阅

在WordPress中,搜索结果页是一个重要的页面,因为它可以让用户轻松地找到他们所需要的内容。在这篇文章中,我们将学习如何制作WordPress搜索结果页。

步骤一:创建搜索结果页模板

首先,您需要在主题文件夹中创建一个名为search.php的文件。这个文件将会成为您的搜索结果页模板。

请注意,搜索结果页不是单独的页面,它只会在用户使用搜索功能时生成。

步骤二:编写搜索结果页代码

在search.php中,您需要编写一些代码来显示搜索结果。以下是一个基本的搜索结果页的代码:

<?php get_header(); ?>

<div id="content" class="site-content">
  <div class="container">
    <div id="primary" class="content-area">
      <main id="main" class="site-main" role="main">

        <?php if ( have_posts() ) : ?>

          <header class="page-header">
            <h1 class="page-title"><?php printf( esc_html__( 'Search Results for: %s', 'yourtheme' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
          </header>

          <?php
          /* Start the Loop */
          while ( have_posts() ) :
            the_post();

            /*
             * Include the Post-Format-specific template for the content.
             * If you want to override this in a child theme, then include a file
             * called content-___.php (where ___ is the Post Format name) and that will be used instead.
             */
            get_template_part( 'template-parts/content', get_post_type() );

          endwhile;

          the_posts_pagination(
            array(
              'prev_text'          => __( 'Previous page', 'yourtheme' ),
              'next_text'          => __( 'Next page', 'yourtheme' ),
              'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'yourtheme' ) . ' </span>',
            )
          );

        else :

          get_template_part( 'template-parts/content', 'none' );

        endif;
        ?>

      </main><!-- #main -->
    </div><!-- #primary -->

  </div><!-- .container -->
</div><!-- #content -->

<?php get_footer(); ?> 

这里,我们首先使用get_header()函数和get_footer()函数呼叫页面的顶部和底部部分。然后,我们创建了一个包含搜索结果的内容区域。

我们使用have_posts()函数来检查是否有搜索结果可用,并使用get_search_query()函数来获取搜索查询。如果有结果,我们使用while循环遍历所有结果,并使用get_template_part()函数来加载模板片段来显示每个结果。

最后,我们使用the_posts_pagination()函数来显示分页链接。

步骤三:添加样式

最后一步是添加样式以美化搜索结果页面。您可以在样式表中添加以下代码:

.header-image {
  display: none;
}

.search-results {
  padding: 40px 0;
}

.search-results .page-title {
  font-size: 30px;
  margin-bottom: 20px;
} 

这里,我们隐藏了页面的标题,添加了一些内边距,增加了标题的大小,以及增加了标题和搜索结果之间的间距。

结论

现在,您已经知道如何创建和自定义WordPress搜索结果页了。您可以添加更多的样式和特定于目标用户的元素来提高用户体验。

阅读文章或者观看视频过程中有任何问题,请下方留言或者联系我Q248758228

大家谈论
    我的见解
    目录