[英]How can I get information from an array from an ACF Image field in WP?
我對 WP 很陌生,所以這似乎是一個非常簡單的問題。 我正在嘗試通過 css class 和高級自定義字段提供背景圖像 url。 我想這樣做,這樣我就可以保持 class 清潔干燥。 該圖像作為自定義字段圖像存儲在 WP admin 中。 這是我的英雄模板代碼:
<?php
if (have_posts()) : while (have_posts()) : the_post();
?>
<?php
$hero_img = get_field('hero_image');
?>
<h3>ACF Field Data: <?php the_field('hero_image');?></h3> // just to see what it is
<section class="panel--hero panel--bg-image" <?php $hero_img ? print 'style="--background-image: url("hero_img[5]");"' : ''; ?>>
<div class="panel__content">
<div class="container container__grid page-heading">
<div class="container__col">
<h2 class="page-title center--flex text-white"><?php the_title() ?></h2>
</div>
</div>
<div>
</section>
<?php
endwhile;
endif;
?>
和scss:
&--bg-image {
position: relative;
height: 50vh;
&::after {
background-image: var(--background-image);
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
bottom: 0;
content: '';
display: block;
opacity: var(--opacity);
left: 0;
right: 0;
position: absolute;
top: 0;
z-index: -1;
}
}
沒有圖像顯示。 絕對路徑是該數組中的第五項,它沒有通過。 在 JS 中,我通常會循環遍歷它,但我認為我已經使用變量聲明上方的“if/while”循環完成了該操作。 我現在還需要循環 $hero_img 變量嗎? 如果是這樣,那是在 WP/PHP 中執行此操作的最常規方法嗎? forEach 是一個選項嗎? 也許我不清楚僅通過運行 if/while 循環就可以獲得數據。 任何幫助將非常感激。! 謝謝。
選項 1 - 使用數組鍵
假設您使用 ACF 並且該字段設置為返回“圖像數組”,您可以使用數組鍵url
,即:
$hero_img_url = $hero_img['url'];
選項 2 - 僅從 ACF 退回 URL
如果您只想獲取圖像的 URL,則可以在字段的 ACF 設置中將返回格式更改為“圖像 URL ”。 然后get_field
只返回 url ,你可以像你已經得到它一樣,例如:
$hero_img_url = get_field('hero_image');
補充說明
var_dump($hero_img);
到 output 到屏幕上究竟有什么鍵和值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.