【问题标题】:Query WP Custom Posts with ACF Taxonomy field使用 ACF 分类字段查询 WP 自定义帖子
【发布时间】:2019-06-27 14:09:24
【问题描述】:

我需要使用 ACT 分类字段查询自定义帖子。我创建了这段代码:

我的分类 ACF 字段返回术语对象并允许多选,但此代码仅适用于最后选择的术语。我需要查询所有选定的术语。

<?php
$album_count = get_sub_field('album-count');
$album = get_sub_field('album-custom-category'); ?>
<?php foreach ( $album as $album ); ?>
<?php $the_query = new WP_Query( 
    array(
    'post_type' => 'gallery',
    'orderby' => 'date',
    'posts_per_page' => 6,
    'tax_query' => array(
        array(
            'taxonomy' => 'albums',
            'field'    => 'slug',
            'terms'    => array( $album->slug ),
        ),
    ),
    )
    ); 
    ?>

我的错误在哪里?

【问题讨论】:

    标签: wordpress advanced-custom-fields


    【解决方案1】:

    您正在对所有术语进行 foreach,然后在 foreach 中设置查询的值,这当然只会引入最后一个术语,因为您每次都会覆盖以前的值。由于它是多选,您应该能够将整个专辑数组传递给 WP_Query。此外,请确保您在 ACF 中返回术语 ID 值,而不是术语对象。然后,您将代码更新为如下所示:

    <?php
    $album_count = get_sub_field('album-count');
    $albums = get_sub_field('album-custom-category'); ?>
    
    <?php $the_query = new WP_Query( 
      array(
        'post_type' => 'gallery',
        'orderby' => 'date',
        'posts_per_page' => 6,
        'tax_query' => array(
          array(
            'taxonomy' => 'albums',
            'field'    => 'term_id', // This line can be removed since it’s the default. Just wanted to show that you’re passing the term is instead of slug.
            'terms'    => $albums,
          ),
        ),
      ),
    ); ?>
    

    【讨论】:

    • 我之前做过,但它给出了一个错误 - 以下部分的所有内容都缺少此代码:/
    • 好的,我明白了——我没有将“slug”更改为“term_id”。现在它是有道理的。非常感谢!
    • 没问题。很高兴我能提供帮助
    猜你喜欢
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    相关资源
    最近更新 更多