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


Wordpress get result from title (anywhere), not just first word

目前这是作为独立search.php查询的工作代码。

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

我有一种感觉,我接近解决方案,我尝试了几件事,这可能是我错过了post $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数组…例如"class…"

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

所以我正确地返回了两个只有"经典"在帖子标题中提到的项目。

如果我输入"som"或"els",它不会返回任何内容,并且应该匹配所有"some"answers"else"项。

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

谢谢!

解决了这个问题会对将来的人有所帮助。

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);
}
相关文章: