簡體   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