首页 文章

如何使用LIKE在wordpress中搜索类别名称的帖子?

提问于
浏览
2
  • 我需要自定义单词按基本搜索过滤器 .

  • 它可以很好地搜索帖子 Headers 和帖子内容中的关键字 .

  • 现在我需要显示结果,如果用户输入与类别名称匹配的名称,那么它应该从该类别以及其他结果中提取结果 .

  • 我假设,它应该类似于在税务查询中对category_name或category_in运算符使用LIKE子句 .

$args = get_posts(array(
            'fields' => 'ids',
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            's' =>  $_REQUEST['s'] ? $_REQUEST['s'] : '' ,
            'tax_query' => array(
                 array(
                'taxonomy' => 'NAME OF TAXONOMY',
                'field'    => 'slug',
                'terms'    => 'SLUG OF the TERM', // LIKE (here should be any LIKE clause etc)
                 ),
            )   
        ));

如何实现这种情况,意味着当用户输入与类别名称匹配的任何关键字时,它应该从该类别中提取所有结果以及常规搜索结果 .

Example: 在搜索栏中,用户写入“ ABC " and there is category available with name " ABC Park ", then it should pull results from this category along with results having post titles and content which contain " ABC” .

1 回答

  • 3

    好的......我想出了一个解决方案,我从表 terms 中获取了LIKE查询的所有类别ID,然后在其他查询中将此数组作为类别参数传递 . 这是代码 .

    $term_ids=array(); 
          $cat_Args="SELECT * FROM $wpdb->terms WHERE name LIKE '%".$_REQUEST['s']."%' ";
          $cats = $wpdb->get_results($cat_Args, OBJECT);
          array_push($term_ids,$cats[0]->term_id);    
    
    
    
    $q1 = get_posts(array(
            'fields' => 'ids',
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            's' =>  $_REQUEST['s'] ? $_REQUEST['s'] : '' 
    
    ));
     $q2 = get_posts(array(
            'fields' => 'ids',
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'category' =>$term_ids
    ));
    $unique = array_unique( array_merge( $q1, $q2 ) );
    
    $posts = get_posts(array(
        'post_type' => 'post',
        'post__in' => $unique,
        'posts_per_page' => -1
    ));
      if ($posts ) : 
    
    foreach( $posts as $post ) :
    //show results
    endforeach;
    endif;
    

    但我还是想要一种更简洁,更精确的方式 . :)

相关问题