2

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
);

1 Answer 1

3

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 );
1
  • Wow. That was incredibly simple. Thanks. This worked perfectly! May 17, 2011 at 16:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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