php 如何显示 Wordpress 搜索结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14802498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:59:52  来源:igfitidea点击:

How to display Wordpress search results?

phpwordpresssearch

提问by Ilja

I've spent a lot of time figuring out why my search is not working in my custom made template. So far I was able to figure out how to include searchform.php file in my header, created search.php file which is currently empty (so at the moment when I search for something I get redirected to a blank page and I think I definitely need something in search.php file to make it work), I was reading all around Wordpress codex but could not find a solution, only useful information I found was this.

我花了很多时间弄清楚为什么我的搜索在我的自定义模板中不起作用。到目前为止,我能够弄清楚如何在我的标题中包含 searchform.php 文件,创建了当前为空的 search.php 文件(所以当我搜索某些内容时,我被重定向到一个空白页面,我想我肯定需要 search.php 文件中的某些内容才能使其工作),我正在阅读 Wordpress 法典的所有内容,但找不到解决方案,我发现的唯一有用信息就是这个。

http://codex.wordpress.org/Creating_a_Search_Page

http://codex.wordpress.org/Creating_a_Search_Page

Can you suggest what need's to be done in order to display results of a search? is there a special query, function etc? I really can't find it anywhere.

您能否建议需要做什么才能显示搜索结果?是否有特殊查询、功能等?我真的在任何地方都找不到。

my searchform.phpfile in case you need it.

我的searchform.php文件,以备不时之需

<form action="<?php echo home_url(); ?>" id="search-form" method="get">
    <input type="text" name="s" id="s" value="type your search" onblur="if(this.value=='')this.value='type your search'"
    onfocus="if(this.value=='type your search')this.value=''" />
    <input type="hidden" value="submit" />
</form>

采纳答案by James Hebden

Basically, you need to include the Wordpress loop in your search.php template to loop through the search results and show them as part of the template.

基本上,您需要在 search.php 模板中包含 Wordpress 循环来循环搜索结果并将它们显示为模板的一部分。

Below is a very basic example from The WordPress Theme Search Template and Page Templateover at ThemeShaper.

下面是ThemeShaper 上的 WordPress 主题搜索模板和页面模板的一个非常基本的示例。

<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package Shape
 * @since Shape 1.0
 */

get_header(); ?>

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

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

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

                <?php shape_content_nav( 'nav-above' ); ?>

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

                    <?php get_template_part( 'content', 'search' ); ?>

                <?php endwhile; ?>

                <?php shape_content_nav( 'nav-below' ); ?>

            <?php else : ?>

                <?php get_template_part( 'no-results', 'search' ); ?>

            <?php endif; ?>

            </div><!-- #content .site-content -->
        </section><!-- #primary .content-area -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

回答by Said Erraoudy

you need to include the Wordpress loop in your search.php this is example

您需要在 search.php 中包含 Wordpress 循环,这是示例

search.phptemplate file:

search.php模板文件:

<?php get_header(); ?>
<?php
$s=get_search_query();
$args = array(
                's' =>$s
            );
    // The Query
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
        _e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
        while ( $the_query->have_posts() ) {
           $the_query->the_post();
                 ?>
                    <li>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </li>
                 <?php
        }
    }else{
?>
        <h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
        <div class="alert alert-info">
          <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
        </div>
<?php } ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

回答by Brownrice

I am using searchform.phpand search.phpfiles as already mentioned, but here I provide the actual code.

我正在使用searchform.phpsearch.php前面提到的文件,但在这里我提供了实际的代码。

Creating a Search Pagecodexpage helps here and #Creating_a_Search_Page_Templateshows the search query.

创建搜索页面codex页面在这里有帮助并#Creating_a_Search_Page_Template显示搜索查询。

In my case I pass the $search_queryarguments to the WP_QueryClass(which can determine if is search query!). I then run The Loopto display the post information I want to, which in my case is the the_permalinkand the_title.

在我的例子中,我将$search_query参数传递给WP_QueryClass(它可以确定是否是搜索查询!)。然后我运行The Loop来显示我想要的帖子信息,在我的例子中是the_permalinkthe_title.

Search box form:

搜索框形式:

<form class="search" method="get" action="<?php echo home_url(); ?>" role="search">
  <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
  <button type="submit" role="button" class="btn btn-default right"/><span class="glyphicon glyphicon-search white"></span></button>
</form>

search.phptemplate file:

search.php模板文件:

<?php
    global $query_string;
    $query_args = explode("&", $query_string);
    $search_query = array();

    foreach($query_args as $key => $string) {
      $query_split = explode("=", $string);
      $search_query[$query_split[0]] = urldecode($query_split[1]);
    } // foreach

    $the_query = new WP_Query($search_query);
    if ( $the_query->have_posts() ) : 
    ?>
    <!-- the loop -->

    <ul>    
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>   
    <?php endwhile; ?>
    </ul>
    <!-- end of the loop -->

    <?php wp_reset_postdata(); ?>

<?php else : ?>
    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

回答by blueray

Check whether your template in themefolder contains search.phpand searchform.phpor not.

检查您的模板是否theme文件夹中包含search.phpsearchform.php与否。

回答by Chandan Kumar Thakur

WordPress include tags, categories and taxonomies in search results

WordPress 在搜索结果中包含标签、类别和分类法

This code is taken from http://atiblog.com/custom-search-results/

此代码取自http://atiblog.com/custom-search-results/

Some functions here are taken from twentynineteen theme.Because it is made on this theme.

这里的一些功能是取自二十十九主题,因为它是在这个主题上制作的。

This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.

此代码示例将帮助您在搜索中包含标签、类别或任何自定义分类法。并显示包含这些标签或类别的帖子。

You need to modify your search.php of your theme to do so.

您需要修改主题的 search.php 才能这样做。

<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) ); 
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );

$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();

foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}

foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}

foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}

$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));

$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {

}

?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {

}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {

}
?>