Wordpress - query_post by title?
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;
}
?>
Then:
$args = array(
'post_title_like' => $str
);
$res = new WP_Query($args);
got this working with the help from this post in the end. Cheers guys;
$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;
Get the title from another loop
$title = get_the_title();
and use the $title variable if you wish.
<?php
global $post, $current_post_id, $title;
function filter_where($where = ''){
global $title;
$where .= "AND post_title = '$title'";
return $where;
}
add_filter('posts_where', 'filter_where');
$query = new WP_Query(array('post_type' => 'sessions') );
if ( have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
/* Loop here */
endwhile; endif;
wp_reset_query(); ?>