Example of WP_Query to search by post title in WordPress
One way to interact with the database is by using the global $wpdb
object in WordPress. $wpdb
is a WordPress database access abstraction class. This class used to interact with a database without needing to use raw SQL statements.
The recommended way to access $wpdb
in your WordPress PHP code is to declare $wpdb
as a global variable, like this:
<?php
// 1st Method - Declaring $wpdb as global and using it to
// execute an SQL query statement that returns a PHP object
global $wpdb;
$query = "
SELECT *
FROM $wpdb->posts
WHERE $wpdb->posts.post_title LIKE '$param2%'
ORDER BY $wpdb->posts.post_title
";
$wpdb->get_results($query);
Alternate way and standard way to solve this operation is using
:filter
<?php
add_filter( 'posts_where', 'qirolab_posts_where', 10, 2 );
function qirolab_posts_where( $where, &$wp_query )
{
global $wpdb;
if ( $title = $wp_query->get( 'search_title' ) ) {
$where .= " AND " . $wpdb->posts . ".post_title LIKE '" . esc_sql( $wpdb->esc_like( $title ) ) . "%'";
}
return $where;
}
Now we can pass the title as the search_title
argument in WP_Query
.
<?php
$args = array(
'post_type' => 'post',
'search_title' => $param,
'posts_per_page' => $page_size,
'paged' => $page,
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
);
$wp_query = new WP_Query( $args );
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
//Your Code to display post...
endwhile;
endif;
Please login or create new account to add your comment.