是否仅按元字段搜索自定义帖子类型帖子?

时间:2018-02-01 作者:Mladen Jankovic

是否可以搜索自定义帖子类型product 通过_sku 或其他带有输入文本字段的自定义元字段?我不想使用插件,只需要自定义WP函数。

我找到了仅按标题搜索的解决方案:

function __search_by_title_only( $search, &$wp_query )
{
    global $wpdb;
    if ( empty( $search ) )
        return $search; // skip processing - no search term in query
    $q = $wp_query->query_vars;
    $n = ! empty( $q[\'exact\'] ) ? \'\' : \'%\';
    $search =
    $searchand = \'\';
    foreach ( (array) $q[\'search_terms\'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}($wpdb->posts.post_title LIKE \'{$n}{$term}{$n}\')";
        $searchand = \' AND \';
     }
     if ( ! empty( $search ) ) {
         $search = " AND ({$search}) ";
         if ( ! is_user_logged_in() )
             $search .= " AND ($wpdb->posts.post_password = \'\') ";
          }
      return $search;
  }
add_filter( \'posts_search\', \'__search_by_title_only\', 500, 2 );
。。。但我需要这样的函数来处理元字段(_sku_author ).

谢谢

1 个回复
SO网友:Anton Flärd

这可能有效,但尚未测试。首先添加此项以加入Posteta表:

add_filter( \'posts_join\', \'search_filters_join\', 501, 2 );

function search_filters_join( $join, $query ) {
    global $wpdb;

    if ( empty( $query->query_vars[ \'post_type\' ] ) || $query->query_vars[ \'post_type\' ] !== \'product\' ) {
        return $join; // skip processing
    }

    if ( ($this->is_ajax_search() || $this->is_search_page()) && !is_admin() ) {

            $join .= " INNER JOIN $wpdb->postmeta AS customsearch ON ( $wpdb->posts.ID = customsearch.post_id )";
    }


    return $join;
}
然后修改$search-foreach循环中的变量,以包括以下内容(此示例显示_sku, 只需添加_author 给另一个人OR 部分(如果您还想搜索):

$search .= "{$searchand} (($wpdb->posts.post_title LIKE \'{$n}{$term}{$n}\') OR (customsearch.meta_key=\'_sku\' AND customsearch.meta_value LIKE \'{$n}{$term}{$n}\'))";

结束