【问题标题】:Custom post type search result within the page页面内的自定义帖子类型搜索结果
【发布时间】:2017-11-22 15:09:44
【问题描述】:

下面的表格给了我确切的结果。我有一个产品自定义帖子,其结果需要在表单下方或下方带有


标签。它没有相应地显示结果。
<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
<label>        
<span class="screen-reader-text">Search for:</span>
<input type="text" name="s" placeholder="Search Product..." id="search">
<input type="submit" id="searchsubmit" value="Search">
<input type="hidden" name="post_type" id="post_type" value="product">
</label>
</form>
<hr>

我的自定义邮政编码 add_action('init', 'product_register');

function product_register() {
    $args = array('label' => __('Products'), 'singular_label' => __('Product'), 'public' => true, 'show_ui' => true, 'capability_type' => 'post', 'hierarchical' => false, 'rewrite' => true, 'supports' => array('title', 'editor', 'thumbnail'));

    register_post_type('product', $args);
}
add_action('admin_init', 'admin_init');

我的搜索结果代码

<div class="container">
     <?php if ( have_posts() && strlen( trim(get_search_query()) ) != 0 ) : ?>
           <h1>Search Results for<small><?php echo get_search_query(); ?></small></h1>
        <?php while ( have_posts() ) : the_post(); ?>
              <?php if ( has_post_thumbnail() ) : ?>
                    <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'medium' ); ?></a>
                 <div class="span9">
              <?php else : ?>
                 <div class="span12">
              <?php endif; ?>
                 <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
              <?php the_excerpt(); ?>
           <hr />
        <?php endwhile; ?>
     <?php else : ?>
        <div class="page-header">
           <h1 class="page-title">No results Found</h1>
        </div>
     <?php endif ;?>
</div><!--/.container -->

请建议显示确切的结果。

【问题讨论】:

    标签: wordpress search custom-post-type


    【解决方案1】:

    你需要在pre_get_posts钩子里面设置自定义帖子类型,在functions.php里面添加这段代码,

    add_filter( 'pre_get_posts', 'add_cpt_in_search_result' );
    
    function add_cpt_in_search_result( $query ) {
    
        if ( $query->is_search ) {
        $query->set( 'post_type', array( 'post', 'page', 'product' ) );
        }
    
        return $query;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-20
      • 2014-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      相关资源
      最近更新 更多