Forums

Querying WordPress database for certain post meta values with regexp (1 post)

  1. whw
    Member
    Posted 4 months ago #

    Hello,

    I'm trying to get a list of posts whose post meta value contains a certain string. The website I'm working with has accreditation for art and videos stored in metadata, and I want to get a list of every art/video a person has worked on. However, because these are not always done by one person (e.g. the meta value could be "John Doe and Jane Doe") I want to get any post whose meta value contains the name "John Doe," but does not necessarily contain it exclusively.

    I tried the following wpdb get_col database query, but it didn't work:

    function getCredit($type, $person) {
    	$getPostIds = $wpdb->get_col("
    	    SELECT p.ID
    	    FROM $wpdb->posts p, $wpdb->postmeta pm
    	    WHERE p.ID = pm.post_id
    	    AND pm.meta_key = '".$type."'
    	    AND pm.meta_value
    	    REGEXP '" . $person . "'"
    	);
    	return $getPostIds;
    }

    This returns the post IDs, then I would use those to get the posts.

    Currently, I'm using the following code, which only finds with meta values that equal the name I'm looking for:

    $args = array('posts_per_page'=> 50, 'meta_key'=>'writer', 'meta_value'=>$title);
    $my_query = new WP_query($args);

    Should I try to use the 'compare' option in my $args array (which I couldn't get to work), or do I need to revise my database query code?

    Thanks

Reply

You must log in to post.

About this Topic