繁体   English   中英

使用“ ACF分类”字段查询WP自定义帖子

[英]Query WP Custom Posts with ACF Taxonomy field

我需要使用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 ),
        ),
    ),
    )
    ); 
    ?>

我的错误在哪里?

您正在对所有术语进行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,
      ),
    ),
  ),
); ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM