扩展站点搜索以包括单个定制字段

时间:2013-09-03 作者:Brob

我的函数中有以下代码。php文件

function __adapted_search_function($search, $query) {
  if(is_admin() || !$query->is_main_query() || !$query->is_search)
    return; //determine if we are modifying the right query

  global $wpdb;
  $search_term = $query->get(\'s\');
  $search = \' AND (\';

  //point 1
  $search .= "($wpdb->posts.post_title LIKE \'%$search_term%\')";

  //need to add an OR between search conditions
  $search .= " OR ";

  //point 2
  $search .= "($wpdb->posts.post_excerpt LIKE \'%$search_term%\')";

  //need to add an OR between search conditions
  $search .= " OR ";

  //point 3
  $search .= "($wpdb->postmeta.meta_key = \'mcb-product\' AND $wpdb->postmeta.meta_value LIKE \'%$search_term%\')";

  //add the filter to join, sql will error out without joining the tables to the query
  add_filter(\'posts_join\', \'__custom_join_tables\');   


  return $search . \') \';
}

function __custom_join_tables($joins) {
  global $wpdb;
  $joins = "JOIN $wpdb->postmeta ON ($wpdb->postmeta.post_ID = $wpdb->posts.ID)";
  return $joins;
}
我希望它只搜索帖子标题、摘录和单个自定义字段。

如果我删除了连接,但确实需要将其包括在内,那么它会起作用,有人能看到我哪里出错了吗?

2 个回复
SO网友:Brob

我通过扩展查询成功解决了此问题

function extend_search( $search, &$wp_query ) {
    global $wpdb;

    if ( empty( $search ))
        return $search;

    $terms = $wp_query->query_vars[ \'s\' ];
    $exploded = explode( \' \', $terms );
    if( $exploded === FALSE || count( $exploded ) == 0 )
        $exploded = array( 0 => $terms );

    $search = \'\';
    foreach( $exploded as $tag ) {
        $search .= " AND (
            ($wpdb->posts.post_title LIKE \'%$tag%\')
            OR ($wpdb->posts.post_excerpt LIKE \'%$tag%\')
            OR EXISTS
            (
                SELECT * FROM $wpdb->postmeta
                WHERE post_ID = pl_posts.ID
                    AND meta_key = \'--KEY--\'
                    AND meta_value LIKE \'%$tag%\'
            )

        )";
    }

    return $search;
}

SO网友:s_ha_dum

pre_get_posts 只接受一个参数,但您似乎在使用它posts_where. 事实并非如此pre_get_posts 作品您必须修改$query 对象,而不是构造并返回SQL 条款

我不可能轻易地测试这个,但我认为你想要的钩子是posts_where 或者posts_search 逻辑上最有意义的过滤器。

add_action(\'posts_where\', \'__adapted_search_function\',1,2);

add_action(\'posts_search\', \'__adapted_search_function\',1,2);
您可能需要修改代码,但更改正在使用的挂钩是关键。

结束

相关推荐

search page different results

我有自定义的帖子类型,并希望根据用户的搜索元数据显示不同的结果。我有三种不同风格的自定义帖子类型,希望根据各自的风格返回搜索结果,而不是当前显示的通用页面链接和摘录。我可以使用is\\u search()吗?<?php if ( is_search() ) : // Only display Excerpts for Search ?> <div class=\"entry-summary\"> <?php the_excerpt(); ?>&#