如果主搜索查询在WordPress中返回零结果,则使用自定义查询

时间:2016-08-02 作者:Raj

我有一个搜索页面,如果主搜索返回0个结果,那么将使用以下查询。

代码为

$num_res = $wp_query->post_count;
$get_search_term = get_search_query();

if($num_res == 0)
{

    $args = array(
        \'post_type\'     => \'resources\',
        \'meta_key\'      => \'resource_txt\',
        \'meta_value\'    => $get_search_term,
        \'meta_compare\'  => \'LIKE\' );
    $custom_query =  new WP_Query( $args );
}
现在我得到一个错误"Not unique table/alias: \'wp_postmeta\'"

当我在浏览器中打印第二个查询时,它会说,

SELECT SQL_CALC_FOUND_ROWS 

DISTINCT wp_posts.ID FROM wp_posts 

INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) 

LEFT JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) 

WHERE 1=1 

AND ( ( wp_postmeta.meta_key = \'resource_txt\' AND CAST(wp_postmeta.meta_value AS CHAR) LIKE \'%insurance claim%\' ) ) 

AND wp_posts.post_type = \'resources\' 

AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'private\') 

GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10
我必须关闭上一个查询,然后运行自定义查询。非常感谢您的帮助。

1 个回复
SO网友:Debakant Mohanty

尝试使用“pre\\u get\\u posts”挂钩,而不是编写另一个查询。有关更多信息,请查看这些文档。

 <?php
function search_posts( $query ) {

    // Make sure this only runs on the main query on the front page
    if ($query->is_main_query() ) {

        // Exclude posts that have been explicitly set to hidden
        $query->set(\'meta_query\', array(
            \'relation\' => \'AND\',
            // Include posts where the meta key isn\'t set
            array(
                \'key\'     => \'resource_txt\',
                \'value\'   => $get_search_term, // A value must exist due to https://core.trac.wordpress.org/ticket/23268
                \'compare\' => \'LIKE\',
            ),
        ) );

    }

}
add_action( \'pre_get_posts\', \'search_posts\' );
?>
希望这有帮助!