Support » Plugins » Hacks » Using Meta query to find value in Custom Field array

  • I am using the Advanced Custom Field Plugin to create references from one custom object to multiple instances of another.

    The plugin stores the multiple references as an array. So for example my post refers to posts 6,17 and 345, the meta value stored is “6,17,345”.

    I am trying to query for a particular post all references to it. I have seen some references to the same problem in this forum. see e.g. here.

    That would suggest :

    $posts = get_posts(array(
    		'numberposts' => -1,
    		'post_type' => 'link',
    		'meta_query' => array(
    				'key' => 'related_to',
    				'value' => get_the_ID(),
    				'compare' => 'LIKE'

    However this is not correct as the following example demonstrates: if the id of the post was ’45’ it would return the reference above that contains ‘345’, but not ’45’.

    In native SQL i could write up a regular expression to do the right thing – what is the right “wordpress” way to get the results I want – just write a custom query ?



Viewing 3 replies - 1 through 3 (of 3 total)
  • Hey Ofer – have you found a fix for this? Running into the same thing.

    Moderator bcworkz


    You can use $wpdb->get_results($sqlquery) to send a native SQL query. $wpdb is a global database object, and $sqlquery would be your custom query. This is an acceptable “wordpress” way.

    Omatan, couple suggestions:
    Advanced Custom Fields allows for relationship field types, are you using that?

    Have you tried "compare"=>"IN" instead of "compare" => "LIKE"?

    What about "type" => "NUMERIC"?

    The reason you are running into a problem I can see are your type parameter for the meta query is set to char (that’s the default). 45 is actually LIKE 345 in terms of a char based LIKE comparison, because it is part of the string 345. NUMERIC will compare the integers

    An easier way to accomplish this though might be with a tax_query and some taxonomy to achieve post association.

    Hope that helps, let me know if you have any questions.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Using Meta query to find value in Custom Field array’ is closed to new replies.