在wordpress主题或插件开发中,如果要查询某个字段下符合条件的文章,一般采用posts_search过滤器和手动写SQL的方法来实现。好消息是,以后不用这么麻烦了,wordpress提供了查询参数用来控制搜索字段。坏消息是,目前该方法受到限制,仅支持特定的几种字段,灵活性不够。
以前的实现方法,WP_Query::parse_query()方法的s参数搜索post_title, post_excerpt, 和post_content字段
现在的方法
复制
<?php
$my_query = new WP_Query(
array(
's' => 'foo',
'post_type' => 'post',
'search_columns' => array( 'post_excerpt' ),
)
);上面的示例将搜索在其摘要(post_excerp列)中包含 foo 的帖子,排除post_title和post_content列。
目前,只允许使用默认的 post_title, post_excerpt 和 post_content 列,但它可能会在 WordPress 的后续版本中得到扩展。
search_columns 参数的默认值为:array( 'post_title', 'post_excerpt', 'post_content' )。





评论 (0)