分享

php – WordPress自定义帖子类型未显示在搜索结果中

 印度阿三17 2019-07-02

我有自定义帖子类型(测验)&在WordPress中搜索.自定义帖子类型未显示在我的搜索结果页面中.我的搜索结果中只显示默认的帖子内容.

以下是我使用的代码

的functions.php
    function create_posttype(){

register_post_type( 'compassquiz',
    array(
        'labels' => array(
            'name' => __( 'Compass Quiz' ),
            'singular_name' => __( 'Compass Quiz' )
        ),
        'taxonomies' => array('post_tag'),
        'public' => true,
        'publicly_queryable' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'free-quiz-bank-exam'),
        'query_var' => true,
        'exclude_from_search' => false,
    )
);}

add_action( 'init', 'create_posttype' );

functions.php中的附加代码

//Read Custom Post types in Search
function filter_search($query) {
    if ($query->is_search) {
    $query->set('post_type', array('post', 'compassquiz'));
    };
    return $query;
};
add_filter('pre_get_posts', 'filter_search');

search.php中

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

    while ( have_posts() ) : the_post();
        get_template_part( 'template-parts/content', 'search' );
    endwhile;
        the_posts_navigation();
    else :
        get_template_part( 'template-parts/content', 'none' );
    endif; 
?>

内容的search.php

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
    </header>

    <div class="entry-summary">
        <?php 
            echo substr(get_the_excerpt(), 0,150) . '...'; 
            echo ('<br><a href="' .get_permalink() . '" class="moretag">Read More &raquo;</a>');
        ?>
    </div><!-- .entry-summary -->
</article><!-- #post-## -->

我在WP Fourm& amp;还有其他stackoverflow问题.但找不到真正有效的解决方案.

解决方法:

在搜索表单中添加此代码.在隐藏字段值中设置自定义帖子类型.

<input type="hidden" name="post_type" value="post type name" />

搜索表单中的多个自定义帖子类型

<input type="hidden" name="post_type" value="posttype1, posttype2, posttype3" />
来源:https://www./content-1-290001.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多