Get all posts WHERE custom_field is LIKE value

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:

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

Related posts

Leave a Reply

1 comment

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