posts_search中的自定义查询

时间:2015-08-16 02:34:06

标签: php mysql wordpress

如何将此查询用作自定义搜索查询?

add_filter('posts_search', 'my_search_is_perfect', 20, 2);
function my_search_is_perfect($search, $wp_query) 
{
   $sWord = 'Zukunft haus';

   return "
       SELECT *, 
              MATCH(post_title) AGAINST('$sWord' IN BOOLEAN MODE) AS Score 
        FROM `wp_posts` 
       INNER JOIN wp_term_relationships ON wp_term_relationships.object_id = ID
             AND wp_term_relationships.term_taxonomy_id = 1
       WHERE MATCH( post_title) AGAINST ('$sWord' IN BOOLEAN MODE) 
         AND `post_status` = 'publish'
         AND `post_type` = 'post'
       ORDER BY score DESC
  "; 
}

查询是正确的(我在phpMyAdmin中检查了这一点)但是在WordPress中我收到了消息,没有结果。

2 个答案:

答案 0 :(得分:6)

在function.php文件中:

add_filter('posts_search', 'my_search_is_perfect', 20, 2);
function my_search_is_perfect() 
{
    global $post;
    global $wpdb;
    $sWord = 'Zukunft haus';

    $sel_query = "SELECT *, 
                          MATCH(post_title) AGAINST('$sWord' IN BOOLEAN MODE) AS Score 
                    FROM ".$wpdb->prefix."posts 
                   INNER JOIN ".$wpdb->prefix."term_relationships ON ".$wpdb->prefix."term_relationships.object_id = ID
                         AND ".$wpdb->prefix."term_relationships.term_taxonomy_id = 1
                   WHERE MATCH( post_title) AGAINST ('$sWord' IN BOOLEAN MODE) 
                     AND post_status = 'publish'
                     AND post_type = 'post'
                   ORDER BY score DESC";
    $totaldata = $wpdb->get_results($sel_query);

    return $totaldata;
}

答案 1 :(得分:0)

根据@Gustavo Straube的建议,最好使用$ wpdb,在这种情况下你应该像这样实现它:

add_filter('posts_search', 'my_search_is_perfect', 20, 2);

function my_search_is_perfect() 
{
    global $wpdb;

    $sWord = 'Zukunft haus';

    $query = "SELECT *, 
                  MATCH(post_title) AGAINST('$sWord' IN BOOLEAN MODE) AS Score 
            FROM `".$wpdb->prefix."_posts` 
           INNER JOIN ".$wpdb->prefix."_term_relationships ON ".$wpdb->prefix."_term_relationships.object_id = ID
                 AND ".$wpdb->prefix."_term_relationships.term_taxonomy_id = 1
           WHERE MATCH( post_title) AGAINST ('$sWord' IN BOOLEAN MODE) 
             AND `post_status` = 'publish'
             AND `post_type` = 'post'
           ORDER BY score DESC";

    $myrows = $wpdb->get_results( $query );

    return $myrows;
}

您可以在https://codex.wordpress.org/Class_Reference/wpdb

中找到更多信息