Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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( "
SELECT DISTINCT ID FROM {$wpdb->posts}
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;
share|improve this question
add comment

2 Answers

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
    setup_postdata($post);

   // use template tags and profit
   the_title();
}

// cleanup after ourselves
wp_reset_postdata();
share|improve this answer
add comment

You can query the post with the keyword like this;

<?php // Post Query
$args=array(
's'      => $keyword, 
);
?>
<?php query_posts($args); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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