问题描述
是否可以使用 WP_Query 或 query_posts 使用标题创建一个循环的帖子?
即
$args = array('post_title'='LIKE '.$str.'% ');
$res = WP_Query($arg);
// the loop...
// trying this now...
$mypostids = $wpdb->get_col("select ID from $wpdb->posts where post_title like 'Abb%' ");
echo count($mypostids).", "; // works but can't echo out array of IDs for the next args?
$args = array(
'post__in'=> $mypostids
);
$res = WP_Query($args);
while( $res->have_posts() ) : $res->the_post(); ...
最佳解决方案
我会这样做:
的 functions.php
<?php
add_filter( 'posts_where', 'title_like_posts_where', 10, 2 );
function title_like_posts_where( $where, &$wp_query ) {
global $wpdb;
if ( $post_title_like = $wp_query->get( 'post_title_like' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE '' . esc_sql( $wpdb->esc_like( $post_title_like ) ) . '%'';
}
return $where;
}
?>
然后:
$args = array(
'post_title_like' => $str
);
$res = WP_Query($arg);
次佳解决方案
得到这个工作与最后的这个职位的帮助。干杯们
$finalArgs = array (
'posts_per_page'=>5,
'order' => 'ASC',
'post_type' => 'school'
);
// Create a new instance
$searchSchools = new WP_Query( $finalArgs );
$mypostids = $wpdb->get_col("select ID from $wpdb->posts where post_title LIKE '".$str."%' ");
$args = array(
'post__in'=> $mypostids,
'post_type'=>'school',
'orderby'=>'title',
'order'=>'asc'
);
$res = new WP_Query($args);
while( $res->have_posts() ) : $res->the_post();
global $post;
$EstablishmentNumber = get_post_meta($post->ID,'EstablishmentNumber', true);
$schl = array('id'=>$EstablishmentNumber, 'label'=>$post->post_title , 'value'=>$EstablishmentNumber );
$matchedSchools[] = $schl;
endwhile;
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。