按 ACF 字段查询帖子不起作用

Val*_*nte 0 wordpress advanced-custom-fields

有很多与我相关的主题,但我仍然没有找到解决方案。我正在尝试通过 ACF 字段(单选按钮)查询帖子,似乎 meta_query 被完全忽略。它返回所有帖子,而不是仅返回符合条件的帖子。我尝试过使用字段键而不是字段名称、其他比较等。似乎没有任何效果。希望您知道可能出了什么问题!这是我的代码:

<?php

    $post_args = array(
        'post_type'      => 'products',
        'posts_per_page' => - 1,
        'status'         => 'publish',
        'meta_query'     => array(
            'relation' => 'AND',
            array(
                'meta_key'   => 'product_taste',
                'meta_value' => array( 'cold' ),
                'compare'    => 'IN',
            ),
            array(
                'meta_key'   => 'product_served',
                'meta_value' => array( 'grated' ),
                'compare'    => 'IN'
            )

        ),
    );
    $query     = new WP_Query( $post_args );

    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) : ?>
            <?php
            $query->the_post();
            ?>

            <h5>
                <?php the_title(); ?>
            </h5>

        <?php endwhile ?>
        <?php wp_reset_postdata();
    }
    ?>
Run Code Online (Sandbox Code Playgroud)

Flu*_*ten 5

  1. 在“meta_query”数组中使用“key”和“value”

您不需要在 meta_query 中使用meta_keyand ...您只需直接在 $args 数组中使用它们。meta_value如果要添加 meta_query 数组,只需使用keyand value,例如

$post_args = array(
    [...]
    'meta_query'     => array(
        array(
            'key'      => 'product_taste',
            'value'    => 'cold',
            'compare'  => 'LIKE',
        ),
    [...]
Run Code Online (Sandbox Code Playgroud)


2.使用值数组查询序列化数据

'compare' => 'IN'当您尝试查询 ACF 数据时,使用值数组也可能会出现问题,因为 ACF 数据可以在数据库中序列化(例如,如果数据位于转发器中)。

由于您只会搜索单个值,因此可以使用LIKE代替IN

把这些放在一起

$post_args = array(
    'post_type'      => 'products',
    'posts_per_page' => - 1,
    'status'         => 'publish',
    'meta_query'     => array(
        'relation' => 'AND',
        array(
            'key'   => 'product_taste',
            'value' => 'cold',
            'compare'    => 'LIKE',
        ),
        array(
            'key'   => 'product_served',
            'value' => 'grated',
            'compare'    => 'LIKE'
        )
    ),
);
$query     = new WP_Query( $post_args );
Run Code Online (Sandbox Code Playgroud)


如果数据已序列化并且您的值可以返回多个匹配项(例如,将匹配“cold”、“colder”、“coldest”等单词),则尝试在值末尾LIKE 'cold'添加分号 ( ),例如;

    [...]
        array(
            'key'   => 'product_taste',
            'value' => 'cold;', // add ; to the end of the value
            'compare'    => 'LIKE',
        ),
        array(
            'key'   => 'product_served',
            'value' => 'grated;', // add ; to the end of the value
            'compare'    => 'LIKE'
        )
    [...]
Run Code Online (Sandbox Code Playgroud)

当值在数据库中序列化时,这将起作用,因为每个项目将用分号分隔。