![](/img/trans.png)
[英]Advanced Custom Fields - looping through repeater subfields and displaying a specific subfield attribute of each repeater field
[英]Advanced Custom Fields (ACF) - loop through repeater checkout field and output single instance of each value
我有一個WordPress頁面,可循環瀏覽產品列表。 使用ACF轉發器字段創建產品。 每個產品都有一個或多個使用復選框字段應用的屬性(例如,淺色,深色,金屬色,彩色)。
目的是查詢頁面上所有產品的復選框轉發器字段,查看分別為每個產品分配了哪些屬性,並輸出所有產品的單個列表(去除重復項)。
例如,如果有十種產品,並且在它們之間用四個唯一屬性標記,則僅輸出四個唯一屬性。
我試過創建一個空數組,然后遍歷整個數組。 電流回路輸出重復的值(例如, light dark light dark light dark
而不是light dark
)
<?php if (have_rows('product')): while (have_rows('product')) : the_row();
$attributes = get_sub_field_object('product_attributes');
$values = $attributes['value'];
if($values) {
$filter_attributes = array();
foreach ($values as $value) {
if (in_array($attributes, $filter_attributes)) {
continue;
}
$filter_attributes[] = $attributes;
echo $value . " ";
}
} endwhile; endif; ?>
您的代碼有很多問題,因此我們確實需要重新開始。 根據您所提供的內容,並且不完全了解ACF中繼器的設置方式,我認為以下內容應該對您有用。
您似乎想要做的是:
product_attributes
獲取所有值 您遇到的主要問題是獲取唯一數組。 有很多方法可以做到這一點,您選擇了最復雜的:)
1.使用in_array檢查以前的值
目前,您正在嘗試通過這種方式來執行此操作,但是邏輯上存在問題。 因此,我建議使用選項2,但是為了完整起見,這是您應該這樣做的方式:
$filter_attributes = array();
if (have_rows('product')): while (have_rows('product')) : the_row();
$attributes = get_sub_field_object('product_attributes');
$values = $attributes['value'];
if($values) {
foreach ($values as $value)
if (!in_array($value, $filter_attributes)) {
$filter_attributes[] = $value;
}
}
} endwhile; endif;
/* display the values on the same line, separated by spaces */
echo implode(" ", $filter_attributes );
2.使用array_unique
此代碼比以前的選項簡單得多。 您將所有值保存到數組中,然后最后使用array_unique
( PHP.net array_unique )。 這樣就無需每次檢查現有值。 例如
$all_attributes = array();
$filter_attributes = array();
if (have_rows('product')): while (have_rows('product')) : the_row();
$attributes = get_sub_field_object('product_attributes');
$values = $attributes['value'];
if($values) {
foreach ($values as $value)
$all_attributes[] = $value; /* Save ALL values */
}
} endwhile; endif;
/* use array_unique to remove duplicates from the array */
$filter_attributes = array_unique ($all_attributes);
/* display the values on the same line, separated by spaces */
echo implode(" ", $filter_attributes );
3.使用陣列鍵
如果將值用於數組鍵,則將確保每個值都是唯一的,因為數組中不允許重復的鍵。 這有點駭人聽聞,但快速又容易:)
$filter_attributes = array();
if (have_rows('product')): while (have_rows('product')) : the_row();
$attributes = get_sub_field_object('product_attributes');
$values = $attributes['value'];
if($values) {
foreach ($values as $value)
/* if $all_attributes[$value] already exists, this will overwrite it
ensuring the array only has unique values */
$all_attributes[$value] = $value;
}
} endwhile; endif;
/* display the values on the same line, separated by spaces */
echo implode(" ", $filter_attributes );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.