問題描述

我有一個搜索字段的博客帖子,但我需要一個其他的自定義帖子類型。如何創建具有不同搜索結果佈局的自定義搜索表單?

最佳解決方案

這是我試過的,並得到一個解決方案 3 步。假設您的自定義帖子類型是”products”

1 。在這裏添加功能碼可以指定 archive-search.php

 function template_chooser($template)
{
  global $wp_query;
  $post_type = get_query_var('post_type');
  if( $wp_query->is_search && $post_type == 'products' )
  {
    return locate_template('archive-search.php');  //  redirect to archive-search.php
  }
  return $template;
}
add_filter('template_include', 'template_chooser');

2 。創建自定義帖子類型的搜索結果模板 (search-archive.php)

        <?php
        /* Template Name: Custom Search */
        get_header(); ?>
        <div class="contentarea">
            <div id="content" class="content_right">
                     <h3>Search Result for : <?php echo "$s"; ?> </h3>
                     <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
                <div id="post-<?php the_ID(); ?>" class="posts">
                     <article>
                    <h4><a href="http://<?php%20the_permalink();%20?>" title="<?php the_title(); ?>"><?php the_title(); ?></a><h4>
                    <p><?php the_exerpt(); ?></p>
                    <p align="right"><a href="http://<?php%20the_permalink();%20?>">Read     More</a></p>
                    <span class="post-meta"> Post By <?php the_author(); ?>
                     | Date : <?php echo date('j F Y'); ?></span>

                    </article><!-- #post -->
                </div>
        <?php endwhile; ?>
    <?php endif; ?>




           </div><!-- content -->
        </div><!-- contentarea -->
        <?php get_sidebar(); ?>
        <?php get_footer(); ?>
  1. 構建搜索表單在此搜索表單中,值”products” 被隱藏,它將僅搜索產品帖子。

     <div>
        <h3>Search Products</h3>
        <form role="search" action="<?php echo site_url('/'); ?>" method="get" id="searchform">
        <input type="text" name="s" placeholder="Search Products"/>
        <input type="hidden" name="post_type" value="products" /> <!-- // hidden 'products' value -->
        <input type="submit" alt="Search" value="Search" />
      </form>
     </div>
    

更多我想鏈接到這裏 http://www.wpbeginner.com/wp-tutorials/how-to-create-advanced-search-form-in-wordpress-for-custom-post-types/

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。