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'm trying to do a MySQL-style search with Wordpress' built-in functions for fetching posts. There's likely a simple way to do this and I'm probably just a little bit off from the solution.

We have posts with custom fields in them. This is legacy data imported as a custom post type with custom_fields being the extra data from our older database. The custom fields are setup like this for each post in Wordpress right now:

key = subject
val = Subject One, Subject Two, Subject Three

I'm trying to fetch all posts where custom_field value is LIKE "Subject Two", as an example. There's probably an easy way to do this that just hasn't hit me yet. Thanks for your help!

I already have a properly working MySQL query. Just wanted to use Wordpress' functions to handle the query instead of me having to do it manually for this theme view. Here's the working example:

// Get posts that match LIKE this subject
$cft_by_subject = $wpdb->get_results(
    "SELECT
        wp_posts.ID,
        wp_posts.post_title,
        wp_posts.post_date,
        wp_posts.post_name,
        wp_postmeta.meta_value
     FROM
        wp_posts,
        wp_postmeta
     WHERE
        (wp_posts.ID = wp_postmeta.post_id) AND
        (wp_posts.post_type = 'our-custom-post-type') AND
        (wp_posts.post_status = 'Publish') AND
        (wp_postmeta.meta_key = 'subject') AND
        (wp_postmeta.meta_value LIKE '%".$this-is-our-subject."%')
     ORDER BY
        wp_posts.ID ASC
    ",
    ARRAY_A
);
share|improve this question

1 Answer 1

up vote 2 down vote accepted

You can use meta_query in WP_Query

$args = array(
    'post_type' => 'post',
    'meta_query' => array(
        array(
            'key' => 'subject',
            'value' => 'Subject Two',
            'compare' => 'LIKE'
        )
    )
 );
$query = new WP_Query( $args );
share|improve this answer
    
Wow. That was incredibly simple. Thanks. This worked perfectly! –  Will Ashworth May 17 '11 at 16:25

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.