【问题标题】:Wordpress search result page first then postWordpress 搜索结果页面首先然后发布
【发布时间】:2018-09-26 00:59:11
【问题描述】:

我尝试为 WP 默认搜索添加一个功能,我想先使其结果到鞋页项目,然后发布项目,但它还没有完全工作。 我没有使用任何插件进行搜索。

这是我的代码(在 function.php 中):

第一个

<?php 
function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', array('page', 'post'));

};
return $query;
};
add_filter('pre_get_posts', 'filter_search');
?>

我尝试的第二个:

<?php
function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', 
       array(
       'post_type'=>'page', 
       'orderby' => 'title',
       'order'   => 'DESC',
       )
       );
} else {
$query->set('post_type', 
       array(
       'post_type'=>'post', 
       'order'   => 'DESC',
       )
       );
};
return $query;
add_filter('pre_get_posts', 'filter_search');
?>

感谢您的帮助!

【问题讨论】:

    标签: php wordpress search


    【解决方案1】:

    您可以尝试使用 SQL CASE 表达式

    add_filter( 'posts_orderby', 'order_search_by_posttype', 10, 2 );
    function order_search_by_posttype( $orderby, $wp_query ){
        if( ! $wp_query->is_admin && $wp_query->is_search ) :
            global $wpdb;
            $orderby =
                "
                CASE WHEN {$wpdb->prefix}posts.post_type = 'page' THEN '1' 
                     WHEN {$wpdb->prefix}posts.post_type = 'post' THEN '2' 
                ELSE {$wpdb->prefix}posts.post_type END ASC, 
                {$wpdb->prefix}posts.post_title ASC";
        endif;
        return $orderby;
    }
    

    我在这里找到了这个解决方案,https://wordpress.stackexchange.com/questions/177650/sort-search-results-by-post-type/177653#177653

    【讨论】:

    • 嗨桑迪普·潘查尔 |非常感谢您的帮助,是否可以隐藏搜索结果的主页?并按标题或相关进行搜索结果排序?谢谢! ——
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多