我已经注册了一个名为“节点”的自定义帖子类型。
当我创建一个基本的WP\\u查询来获取这种类型的帖子时,它工作得很好。示例:
$args = array(
\'post_status\' => \'publish\',
\'post_type\' => \'node\');
$query = new WP_Query($args);
这将获取类型为“node”的所有已发布帖子。
然而,只要我将此与搜索结合起来,就不会返回任何内容。示例:
$args = array(
\'post_status\' => \'publish\',
\'post_type\' => \'node\',
\'s\' => \'My search term\');
$query = new WP_Query($args);
这将一无所获,尽管它应该得到几个包含“我的搜索词”的“node”类型的帖子。
据我所知,只要我在$args中包含“s”参数,帖子类型就会自动设置为“post”和“page”。如果我打印出一个var\\u dump of$query,它会显示以下内容:
无“s”:
object(WP_Query)
public \'query\' =>
array (size=2)
\'post_status\' => string \'publish\' (length=7)
\'post_type\' => string \'node\' (length=4)
public \'query_vars\' =>
array (size=63)
\'post_status\' => string \'publish\' (length=7)
\'post_type\' => string \'node\' (length=4)
...
带“s”:
object(WP_Query)
public \'query\' =>
array (size=2)
\'post_status\' => string \'publish\' (length=7)
\'s\' => string \'My search term\' (length=14)
\'post_type\' => string \'node\' (length=4)
public \'query_vars\' =>
array (size=66)
\'post_status\' => string \'publish\' (length=7)
\'s\' => string \'My search term\' (length=14)
\'post_type\' =>
array (size=2)
0 => string \'post\' (length=4)
1 => string \'page\' (length=4)
...
因此,Wordpress似乎会在涉及搜索时覆盖帖子类型。
我怎样才能解决这个问题?
SO网友:Tristan CHARBONNIER
在股票WordPress安装中,WP\\u Query将默认为post_type
= \'post\'
.
考虑以下简单示例:
$args = array(
"posts_per_page"=>5,
"ignore_sticky_posts"=>true
);
$itposts = new WP_Query( $args );
它将导致执行以下查询:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = \'post\' AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'private\') ORDER BY wp_posts.post_date DESC LIMIT 0, 5
THE BEST SOLUTION
解决方案是添加
post_type
参数设置为
\'any\'
. 通过这种方式,WordPress将自动在所有类型中进行搜索,除了修订版和具有
exclude_from_search
设置为
true
. 问题,默认情况下,附件不会从搜索中排除。只要你没有
post_status
参数设置为
\'inherit\'
, 你不应该生气,因为附件总是
post_status
设置为
\'inherit\'
.
这样,查询将更改为:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type IN (\'post\', \'page\', \'attachment\') AND (wp_posts.post_status = \'publish\' OR wp_posts.post_author = 1 AND wp_posts.post_status = \'private\') ORDER BY wp_posts.post_date DESC LIMIT 0, 5
如果需要,可以使用以下代码从搜索中排除附件:
add_action(\'init\', \'exclude_attachments_from_search\');
function exclude_attachments_from_search() {
global $wp_post_types;
$wp_post_types[\'attachment\']->exclude_from_search = true;
}