php Wordpress:WP_Query 如何使用自定义帖子类型应用搜索条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8358595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:30:51  来源:igfitidea点击:

Wordpress: WP_Query how to apply search criteria with custom post type

phpwordpresscustom-post-type

提问by Samik Chattopadhyay

I have a custom post type, photo, and need to search for photos matching the title or description with the search keyword with various criteria: contains LIKE %$search_term%, starts with LIKE $search_term%etc. I have the following query, but this doesn't filter records according to $search_term. Please direct me to the right direction to embed this requirement with this query.

我有一个自定义帖子类型 ,photo并且需要使用各种条件搜索与标题或描述匹配的照片:包含LIKE %$search_term%、开头LIKE $search_term%等。我有以下查询,但这不会根据 过滤记录$search_term。请指导我在正确的方向上将此要求嵌入到此查询中。

$search_term = $_GET['term'];
$search_criteria = $_GET['type'];

$loop = new WP_Query( array(
    'post_type' => 'photo',
    'posts_per_page' => 12,
    'orderby'=> 'post_date'
));

Please be nice with me, I am a newbie in Wordpress and don't even know if I am asking a foolish question. But I am really stuck with it and need a solution. Any help will be appreciated a lot. Thank you everybody.

请善待我,我是 Wordpress 的新手,甚至不知道我是否在问一个愚蠢的问题。但我真的被它困住了,需要一个解决方案。任何帮助将不胜感激。谢谢大家。

回答by Prakash Raman

Add the "s" key to your existing arguments array:

将“s”键添加到现有参数数组中:

$loop = new WP_Query( array(
    'post_type' => 'photo',
    'posts_per_page' => 12,
    'orderby' => 'post_date',
    's' => 'search_term'
));

Documentation can be found at: http://codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter

可以在以下位置找到文档:http: //codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter

回答by RichestSoft

Pass your search string here example like this ( 's'=>'test' )

在此处传递您的搜索字符串示例( 's'=>'test' )

 <?php

 /*pass your search string here example like this ( 's'=>'test' ) */
 $args=array('s'=>'test','order'=> 'DESC', 'posts_per_page'=>get_option('posts_per_page'));

   $query=new WP_Query($args);

  if( $query->have_posts()): 

  while( $query->have_posts()): $query->the_post();

 {
   echo $post->post_title;
   echo $post->post_content;
 }

 endwhile; 
 else:
 endif;

 ?>