这里的答案都没有回答你真正的问题:
如何查询 JUST 帖子标题
“原始 SQL”方式:
几个重要的事情:
- 逃避对 SQL 的搜索!(对于标签搜索也这样做!)使用
$GLOBALS['wpdb']->esc_like()
- 如果您只需要 1 列,则可以使用
$GLOBALS['wpdb']->get_col()
$GLOBALS['wpdb']->get_results()
is 如果您想在一行中获取更多列
- 用于
$GLOBALS['wpdb']->tableBaseName
使您的代码可移植 - 处理前缀
,例如$GLOBALS['wpdb']->posts
- 查询帖子时,您还必须考虑要查询的post_type和post_status
=> 通常post_status
您想要的是publish
,但post_type
可能会因您想要的内容而异
- WordPress 表“帖子”包含所有帖子类型 - 帖子、页面、自定义,还包括导航、联系表格等!=> 我强烈建议
post_type
在 WHERE 中使用显式条件!:)
...$GLOBALS
与全球化变量相同-今天的性能差异很小
<?php
// to get ALL published post titles of ALL post types (posts, pages, custom post types, ...
$search_post_titles = $GLOBALS['wpdb']->get_col(
"SELECT post_title from {$GLOBALS['wpdb']->posts}
WHERE (
(post_status = 'publish')
AND
(post_title LIKE '{$GLOBALS['wpdb']->esc_like($search)}%')
)
ORDER BY post_title ASC
"); // I also added ordering by title (ascending)
// to only get post titles of Posts(Blog)
// you would add this to conditions inside the WHERE()
// AND (post_type = 'post')
// for Posts&Pages
// AND ((post_type = 'post') OR (post_type = 'page'))
// test output:
foreach ($search_post_titles as $my_title) {
echo $my_title . " ";
}
?>
WP_Query 方式
这是更多的 wordpress,但有一点开销,因为虽然/有一个fields
参数,但它只有选项:
'all' - 所有字段(也是默认值),'ids' - 只是 ids,'id=>parent' - 。 ..如果你通过其他任何东西,你仍然会得到 all,所以你仍然需要添加“all”但是- WP 但是有用于更改 SELECT 中的字段的过滤器。new WP_Query()
get_posts()
我试图使它与原始 SQL 版本相同,但这取决于 WP 如何进行“搜索” ——我认为这是%search%
1 个单词 + 如果有更多单词,则需要更多逻辑。您可以利用$clauses
用于fields
添加自定义的过滤器来代替添加到's'
$args
的位置(请记住附加到不丢失现有的 WHEREs )$clauses['where' .= "AND ...;
。在post_type => 'any'
导航、联系表格等情况下,也不总是产生与原始查询相同的结果......
WP_Query 还清理输入变量,所以实际上不要逃避$args
!
<?php
$args = [
'fields' => 'all', // must give all here and filter SELECT(fields) clause later!
'posts_per_page' => -1, // -1 == get all
'post_status' => 'publish',
's' => $search,
// I also added ordering by title (ascending):
'orderby' => 'title',
'order' => 'ASC',
'post_type' => 'any', // all "normal" post types
// 'post_type' => 'post', // only "blog" Posts
// 'post_type' => ['post', 'page'], // only blog Posts & Pages
];
$onlyTitlesFilter = function($clauses, $query) {
// "fields" overrides the column list after "SELECT" in query
$clauses['fields'] = "{$GLOBALS['wpdb']->posts}.post_title";
return $clauses; // !FILTER! MUST RETURN!
};
$onlyTitlesFilterPriority = 999;
// add filter only for this query
add_filter('posts_clauses', $onlyTitlesFilter, $onlyTitlesFilterPriority, 2);
// Pro-tip: don't use variable names like $post, $posts - they conflict with WP globals!
$my_posts = (new WP_Query($args))->get_posts();
// !IMPORTANT!
// !remove the filter right after so we don't affect other queries!
remove_filter('posts_clauses', $onlyTitlesFilter, $onlyTitlesFilterPriority);
// test output:
// note that I used "my"_post NOT just $post (that's a global!)
foreach($my_posts as $my_post) {
echo $my_post->post_title . " ";
}
?>
不要混淆 - 你仍然会得到数组WP_Posts
- WP 会向其中抛出一些默认属性和值,但实际上它只会查询和填写你在过滤器中指定的字段的真实值。
PS:我已经测试过这些 - 它们是工作代码(至少在 WP 5.4 和 PHP7 上 :))