首页 > 解决方案 > 如何使用选择器高级自定义字段为自定义帖子类型指定查询?

问题描述

我正在尝试过滤我的“广告系列”自定义帖子类型,并且只显示选择高级自定义字段设置为“精选广告系列”的帖子。选择 acf 的值只能为“精选广告系列”或“非精选广告系列”

到目前为止,这是我的代码,但不是显示带有“精选广告系列”选择的“广告系列”,而是显示了最近上传的“广告系列”

任何帮助,将不胜感激。提前致谢!

<?php
    $args = array(
        'posts_per_page' => 1,
        'post_status' => 'publish',
        'post_type' => 'campaigns',
        'meta_query' => array (
             'key' => 'featured',
             'value' => 'Featured Campaign'
        )
    );
    query_posts( $args );
    if (have_posts()) :
        while (have_posts()) : the_post();
            ?>
            <div class="post">
                <?php the_post_thumbnail(); ?>
                <h3 class="post__title heading--primary u-uppercase"><?php the_title(); ?></h3>
                <p class="text-color--primary"><?php the_field(campaign_category); ?></p>
            </div>
        <?php
        endwhile;
        wp_reset_query();
    endif;
    ?>

标签: phpwordpressadvanced-custom-fieldscustom-post-type

解决方案


感谢评论区的CBroe,答案如下:

meta_query需要嵌套数组,即使是在一个查询的情况下。$args 数组已更改为,现在可以按预期工作:

$args = array(
    'posts_per_page' => 1,
    'post_status' => 'publish',
    'post_type' => 'campaigns',
    'meta_query' => array (
        array (
            'key' => 'featured',
            'value => 'Featured Campaign'
        )
    )
);

推荐阅读