WordPress-在搜索结果中仅显示具有特定模板的页面

我只想在WP搜索结果中显示带有特定模板的页面, 因为我尝试构建没有任何插件的产品目录。纯WP代码。有些页面是我的产品, 并且它们具有product.php模板文件。这是我的search.php:

<?php
    if ( have_posts() ) :
        while ( have_posts() ) :
            the_post();
            get_template_part( 'template-parts/post/content', 'excerpt' );
        endwhile;
        the_posts_pagination();
    else :
        ?>
        <p><?php _e( 'No results.' ); ?></p>
        <?php
            get_search_form();
    endif;
?>

问题是, 如何仅显示我的产品页面而不显示其他页面?


#1


试试看!此功能将中断搜索查询, 并为查询添加一些条件以返回特定页面。

//Filter the search for only posts and parts
function SearchFilter($query)
{
    // Now filter the posts
    if ($query->is_main_query() & $query->is_search && $search_template) {
        $query->set('post_type', 'page');
        $query->set('meta_key' => '_wp_page_template', );
        $query->set('meta_value' => 'product.php');
    }
   // Returning the query after it has been modified
    return $query;
}

add_action('pre_get_posts', 'SearchFilter');

解释代码:

” post_type”将限制此过滤器仅用于页面帖子类型。

条件将限制此过滤器仅在搜索查询上起作用, 而不是在每次调用post查询时都起作用。

 $query->is_search && $search_template

这些参数将通过包含页面模板的meta_key” _wp_page_template”过滤返回的帖子, 因此我们仅返回带有页面模板” product.php”的页面。

        $query->set('meta_key' => '_wp_page_template', );
        $query->set('meta_value' => 'product.php');

来源:

https://www.srcmini02.com/64299.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_37480.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?