Wordpress从标题(任何地方)获得结果,而不仅仅是第一个单词

时间:2015-07-08 09:58:19

标签: php arrays ajax wordpress wordpress-theming

目前,这是一个工作代码,可以作为独立的search.php。

进行查询

我有一个问题是它搜索标题的开头而不是标题中的任何地方,我真正需要的是什么。

我有一种感觉,我接近解决方案,我尝试了几件事情,这可能是我在帖子$ args中遗漏的东西..

global $wp_query;
$type = 'qa';
$args=array(
  'post_type' => $type,
  'post_status' => 'publish',
      'showposts'=>100,
      'orderby'=> 'menu_order',
      'order' => 'DESC'
);
$my_query = null;
$my_query = new WP_Query($args);
$data = array();
if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post();
      $title = get_the_title();
      $url = get_the_permalink();
      $data[$title] = $url;
  endwhile;
}

if(isset($_POST['latestQuery'])){
 $latestQuery = $_POST['latestQuery'];
 $latestQueryLength = strlen($latestQuery);
 $result = array();
 foreach($data as $name => $url){
   if (substr(strtolower($name),0,$latestQueryLength) == strtolower($latestQuery)){
       $result[$name] = $url;
   }
 }
 echo json_encode($result);
}

这已经在本地环境中运行了。

JavaScript查询search.php文件(上面),它根据查询返回json数组...例如“cla ..”

{"Classic something":"http:\/\/www.something\/qa2","Classic something else":"http:\/\/www.something\/qa"} 

所以我已经正确地重新调整了两个只有帖子标题中提到的“经典”的项目。

如果我输入“som”或“els”,它不会返回任何内容,它也应该匹配所有“some”和“else”项目。

我认为这不是javascript代码的问题,而是使用PHP代码。

谢谢!

1 个答案:

答案 0 :(得分:0)

解决了如果将来对某人有所帮助。

if(isset($_POST['latestQuery'])){
 $latestQuery = $_POST['latestQuery'];


global $wp_query;
$type = 'qa';
$args=array(
  'post_type' => $type,
  'post_status' => 'publish',
  's' => "$latestQuery", // defined query
      'showposts'=>100,
      'orderby'=> 'menu_order',
      'order' => 'DESC',
);
$my_query = null;
$my_query = new WP_Query($args);
$data = array();
if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post();
      $title = get_the_title();
      $url = get_the_permalink();
      $data[$title] = $url;
  endwhile;
}

 $result = array();
 foreach($data as $name => $url){ // removed if
       $result[$name] = $url;
 }
 echo json_encode($result);
}
相关问题