Meta Query Posts by Sub Field Value ACF

馋奶兔 提交于 2019-12-06 09:58:28

问题


I am attempting to query posts by those with sub field values of 'audi'. I have looked and looked but cannot find an answer. The $args I have are below, and posts exist in the database which match 'audi' as the value for sub field 'model' of repeater 'cars'.

$args = array(
    'post_type' => 'manufacturers',
    'meta_query' => array(
       array(
        'key' => 'cars_%_model',
        'value' => 'audi',
        'compare' => 'LIKE'
       )
    )
);
$query = new WP_Query($args);

Any hints as to where this code falls down would be really appreciated.


回答1:


I spent a few hours on this and have a solution for you:

First thing you need to do is setup a filter which replaces '=' comparisons with 'LIKE' comparisons (include this above your previous code):

function my_posts_where( $where ) {
     $where = str_replace("meta_key = 'cars_", "meta_key LIKE 'cars_", $where);
     // note if using wordpress < v4.8.3 add a % to the meta key like this: meta_key = 'cars_%",...
     return $where;
}

add_filter('posts_where', 'my_posts_where');

Now all you need to do is update your meta_query comparison to '=':

$args = array(
    'post_type' => 'manufacturers',
    'meta_query' => array(
       array(
        'key' => 'cars_%_model',
        'value' => 'audi',
        'compare' => '='
       )
    )
);
$query = new WP_Query($args);

This is included in the ACF documentation however the documentation does not mention the updates following Wordpress 4.8.3 which is mentioned here.



来源:https://stackoverflow.com/questions/38312487/meta-query-posts-by-sub-field-value-acf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!