查询ACF中继器字段

时间:2018-04-26 09:17:40

标签: php wordpress custom-post-type advanced-custom-fields

我想查询ACF转发器字段。我有一个名为图书馆的转发器字段(在CPT中称为图书),在此转发器中,我有一个名为图书馆的关系字段(已连接到名为的其他自定义帖子类型。我想查询这个字段*。

我期待恢复,感谢用户提供的独特价值(由于选择而选择),所有与此图书馆相关的图书。

Ex :选择“图书馆1”。回归:'哈利波特1'和'哈利波特2'。

试验(不工作)

function my_posts_where( $where ) {

$where = str_replace("meta_key = 'library_$", "meta_key LIKE 'library_%", $where);
return $where; } add_filter('posts_where', 'my_posts_where');
$library= $_GET['library'];

$v_args = array(
        'post_type'     =>  'book', 
        'meta_query'    =>  array(
                                array(
                                    'key'     => 'library_$_library',
                                    'compare' => '=', 
                                    'value'   => $library, 
                                ),
                            )
    ); $Query = new WP_Query($v_args);

    if($Query->have_posts()) :
        while($Query->have_posts()) : $Query->the_post();
            ...
        endwhile;

    else : 
        ...
    endif;

这个

    $library= $_GET['library'];

    $v_args = array(
        'post_type'     =>  'book', 
        'meta_query'    =>  array(
                                array(
                                    'key'     => 'library',
                                    'value'   => $library,
                                    'compare' => 'LIKE', 
                                ),
                            )
    );

$Query = new WP_Query($v_args); 

我在互联网上搜索,我无法解决我的问题......

非常感谢。

- *:我还有一个名为标签的转发器字段,其中包含与标签相关的分类字段。我想展示所有带有标签的书籍。

1 个答案:

答案 0 :(得分:0)

这有点晚了,但是如果这对其他人有帮助,这对我有用:

//Since the changed behaviour of esc_sql() in WordPress 4.8.3, 
//cannot use the % character as a placeholder, hence need to alter 'where' close:
function my_posts_where( $where ) {
    $where = str_replace("meta_key = 'library_$", "meta_key LIKE 'library_%", $where);
    return $where;
}
add_filter('posts_where', 'my_posts_where');

$library_id = $_GET['library']; //get querystr var

$args = array(
     'post_type'      => 'book',
     'posts_per_page' => -1,
     'meta_query'     => array(
          array(
               'key' => 'library_$_library', // our repeater field post object
               'value' => '"'. $library_id .'"', //matches exactly "123", not just 123 - prevents a match for "1234"
               'compare' => 'LIKE'
          )
     )
);
$query = new WP_Query($args);

if ($query->have_posts()): 
    while ($query->have_posts()) : $query->the_post();
        echo $post->post_title.'<br>';
    endwhile; 
endif;

wp_reset_query();