I need some help regarding Custom Query by keyword.

I send a keyword to my page where I would like to list those posts which post_title contains the keyword I sent.

Here comes my query as follows:

$q = 'SELECT guid, post_content, post_title, post_parent, post_type FROM wp_posts WHERE (post_title REGEXP '".$keyword."') AND post_type="attachment"';

How would it be possible to implement it into Wordpress and make it work?

I have seen many snipets but it's really hard for me to make it work.

I have found a code which seemed good, but the displaying part is missing, please see at the end of this question.

global $wpdb;
// If you use a custom search form
$keyword = sanitize_text_field( $_REQUEST['mykey'] );
// If you use default WordPress search form
// $keyword = get_search_query();
$keyword = "%{$keyword}%";
// Search in all custom fields
$post_ids_meta = $wpdb->get_col( $wpdb->prepare( "
SELECT DISTINCT post_id FROM {$wpdb->postmeta}
WHERE meta_value LIKE '%s'
", $keyword ) );
// Search in post_title and post_content
$post_ids_post = $wpdb->get_col( $wpdb->prepare( "
WHERE post_title LIKE '%s'
OR post_content LIKE '%s'
", $keyword, $keyword ) );
$post_ids = array_merge( $post_ids_meta, $post_ids_post );
// Query arguments
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'post__in' => $post_ids,
$query = new WP_Query( $args );
if ( $query->have_posts() ): while ( $query->have_posts() ) : $query->the_post();
// Do loop here
endwhile; endif;

2 Answers 2


Codex has quite an extensive article on this - Displaying Posts Using a Custom Select Query.

In a nutshell:

// retrieve posts using our custom SQL (note that you should query * rather than pick fields)
$posts = $wpdb->get_results($query, OBJECT);

// this is global variable that WP functions rely on for output
global $post;

// loop
foreach($posts as $post) {

    // get global stuff filled current post

   // use template tags and profit

// cleanup after ourselves

You can query the post with the keyword like this;

<?php // Post Query
's'      => $keyword, 
<?php query_posts($args); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.