【问题标题】:Wordpress get result from title (anywhere), not just first wordWordpress 从标题(任何地方)获取结果,而不仅仅是第一个单词
【发布时间】:2015-07-08 09:58:18
【问题描述】:

目前这是作为独立 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 代码的问题。

谢谢!

【问题讨论】:

  • 您是否尝试创建自定义搜索?
  • 嗨 ThemesCreator。我刚刚更新了主帖,因为我无法格式化评论。

标签: php arrays ajax wordpress wordpress-theming


【解决方案1】:

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

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-10
    • 2015-02-26
    • 2019-11-05
    • 1970-01-01
    • 2017-06-04
    • 2023-03-09
    • 1970-01-01
    • 2012-09-03
    相关资源
    最近更新 更多