【发布时间】:2014-09-26 01:22:28
【问题描述】:
我正在尝试为 WordPress 创建一个小型搜索功能。 AJAX 调用应该获取标题为%quote% 的所有帖子。
是否有可能在 get_posts() 函数中实现这一点?
不要误会我的意思。 ajax 工作正常。我的functions.php中有ajax函数,我收到了帖子。这只是我找不到解决方案的“标题喜欢”部分。
【问题讨论】:
我正在尝试为 WordPress 创建一个小型搜索功能。 AJAX 调用应该获取标题为%quote% 的所有帖子。
是否有可能在 get_posts() 函数中实现这一点?
不要误会我的意思。 ajax 工作正常。我的functions.php中有ajax函数,我收到了帖子。这只是我找不到解决方案的“标题喜欢”部分。
【问题讨论】:
您也可以进行自定义搜索查询。
$search_query = "SELECT ID FROM {$wpdb->prefix}posts
WHERE post_type = 'post'
AND post_title LIKE %s";
$like = '%' . $quote . '%';
$results = $wpdb->get_results($wpdb->prepare($search_query, $like), ARRAY_A);
$quote_ids = array_column($results, 'ID');
$quotes = get_posts(array('post_type'=>'post', 'orderby'=>'title', 'order'=>'ASC', 'post__in' => $quote_ids));
【讨论】:
不,但您可以创建自定义循环。
编辑:
$args = array('s' => 'keyword');
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
//whatever you want to do with each post
}
} else {
// no posts found
}
【讨论】:
while,我可以从if 语句中的帖子中获取一个字段吗?
$posts = $wp_query->posts; 而不是while,这导致我的页面的其余部分无法生成。感谢您的答复。我 +1 是因为你的帖子帮助我找到了正确的方向。
或者您可以像这样使用过滤器posts_where:
$options = array(
'posts_per_page' => -1,
'suppress_filters' => false, // important!
'post_type' => 'post',
'post_status' => 'publish',
);
$keyword = 'quote';
add_filter( 'posts_where', 'my_filter_post_where' );
$posts = get_posts( $options );
remove_filter( 'posts_where', 'my_filter_post_where' );
function my_filter_post_where( $where) {
global $wpdb;
global $keyword;
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $keyword ) ) . '%\'';
return $where;
}
【讨论】: