WordPress自定义搜索页面分页返回404

时间:2016-02-05 作者:Anna Gabrielyan

我做了很多研究,测试了很多推荐的代码,但仍然找不到正确的方法来实现它。分页链接不工作。它将我导航到404页(在/?s=ddd页上找不到任何内容)。在某些情况下,它是有效的,但无法理解为什么不适用于所有情况(WORKS )这是我正在使用的代码。奇怪的是,这段代码在其他网站上运行得很好(LINK ), 但在(link ) . Permalinks被设置为“/%category%/%postname%/”,但我已经用其他类型进行了测试。仍然没有结果。

global $wpdb;
global $wp_query;
// If you use a custom search form
// $keyword = sanitize_text_field( $_POST[\'keyword\'] );
// If you use default WordPress search form
$keyword = get_search_query();
$keyword_meta = \'%\'.like_escape( $keyword ) . \'%\';
$keyword_title = like_escape( $keyword ) . \'%\';
$post_title_ids = $wpdb->get_col( $wpdb->prepare( "SELECT {$wpdb->posts}.ID FROM {$wpdb->posts} 
        WHERE {$wpdb->posts}.post_title LIKE \'%s\'", $keyword_title ) );

// Search in all custom fields
$post_ids_meta = $wpdb->get_col( $wpdb->prepare( "SELECT {$wpdb->posts}.ID FROM {$wpdb->postmeta} 
    LEFT JOIN {$wpdb->posts} ON {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id
        WHERE (meta_key = \'_key\' AND meta_value LIKE \'%s\') GROUP BY {$wpdb->posts}.ID", $keyword_meta ) );

$paged =(get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
$post_ids = array_merge($post_title_ids,$post_ids_meta);
// Query arguments
$args = array(      
    \'post_status\' => \'publish\',
    \'paged\' => $paged,
    \'orderby\'=>\'post__in\',
    \'post__in\' => $post_ids
);

$query = new WP_Query ( $args );
//set_include_order($query, $post_ids);

$temp = $wp_query; 
  $wp_query = null; 
  $wp_query = $query;

if ($query->have_posts() ):
    while ($query->have_posts() ) : $query->the_post(); ?>
.
.
HTML
.
.
<?php endwhile; 
endif;?>


<div class="paged_links">
            <?php                   
            $big = 999999999; // need an unlikely integer           
            echo paginate_links( array(
                \'base\' => str_replace( $big, \'%#%\', esc_url( get_pagenum_link( $big ) ) ),
                \'format\' => \'?paged=%#%\',
                \'posts_per_page\' => 10,
                \'current\' => max( 1, get_query_var(\'paged\') ),
                \'total\' => $query->max_num_pages,
                \'mid_size\'=>2,
                \'next_text\'=>_("&raquo;"),
                \'prev_text\'=>_("&laquo;"),
            ) );
            $wp_query = null; 
            $wp_query = $temp; 
             ?>
    </div>

1 个回复
最合适的回答,由SO网友:cybmeta 整理而成

您应该使用pre_get_post 更改搜索查询的操作。这是一种更好的方法,您可以避免不必要的查询(实际上,在您的代码中,WordPress已经对当前请求执行了数据库查询,但您放弃了它并执行了新的数据库查询)。

add_action( \'pre_get_posts\', \'custom_search_query\' );
function custom_search_query( $query ) {
    // Alter only main query, in frontend and for search requests
    if( $query->is_search && ! is_admin() && $query->is_main_query() ) {

        $meta_query = array(
            \'relation\' => \'OR\'
        );
        $meta_query[] = array(
            \'key\'     => \'some_key\',
            \'value\'   => get_search_query(),
           \' compare\' => \'LIKE\',
        );
        $meta_query[] = array(
           \'key\'     => \'some_other_key\',
           \'value\'   => get_search_query(),
           \'compare\' => \'LIKE\',
        );

        // The \'OR\' relation make that posts
        // are required to match at least one the meta queries.
        // If that is not what you want, we need some other logic
        // Maybe including a fake meta query that always verify to true?

        $query->set( \'meta_query\', $meta_query );

    }
}
如果要包括任何自定义字段,即使是不知道的自定义字段,也需要过滤主查询的join和where子句(source):

<?php
/**
 * Extend WordPress search to include custom fields
 *
 * http://adambalee.com
 */

/**
 * Join posts and postmeta tables
 *
 * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
 */
function cf_search_join( $join ) {
    global $wpdb;

    if ( is_search() ) {    
        $join .=\' LEFT JOIN \'.$wpdb->postmeta. \' ON \'. $wpdb->posts . \'.ID = \' . $wpdb->postmeta . \'.post_id \';
    }

    return $join;
}
add_filter(\'posts_join\', \'cf_search_join\' );

/**
 * Modify the search query with posts_where
 *
 * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
 */
function cf_search_where( $where ) {
    global $pagenow, $wpdb;

    if ( is_search() ) {
        $where = preg_replace(
            "/\\(\\s*".$wpdb->posts.".post_title\\s+LIKE\\s*(\\\'[^\\\']+\\\')\\s*\\)/",
            "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
    }

    return $where;
}
add_filter( \'posts_where\', \'cf_search_where\' );

/**
 * Prevent duplicates
 *
 * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
 */
function cf_search_distinct( $where ) {
    global $wpdb;

    if ( is_search() ) {
        return "DISTINCT";
    }

    return $where;
}
add_filter( \'posts_distinct\', \'cf_search_distinct\' );
?>
现在您可以使用标准模板层次结构,不需要自定义分页内容,并避免不必要的数据库查询。

相关推荐

在wp-json/wp/v2/Search中添加帖子字段

我正在尝试在wp-json/wp/v2/search 获取端点,但此端点似乎没有考虑register_rest_field 方法add_action(\'rest_api_init\', function() { register_rest_field(\'post\', \'excerpt\', array( \'get_callback\' => function ($post_arr) { die(var_dump($post_arr)