显示组中的整个字段(文件 + ACF)



我用文件下载了ACF插件组。在组中,我有字段"文件 1"、"文件 2"...等。 我想将所有附件显示到页面。是否可以显示属于组的所有字段?我尝试使用基本代码,但在这种情况下,我只有 1 个文件。

如何添加迭代或显示所有字段?

<?php
$file = get_field('attachment_1');
if( $file ): 
// vars
$url = $file['url'];
$title = $file['title'];
$caption = $file['caption'];
if( $caption ): ?>
<div class="wp-caption">
<?php endif; ?>
<ul>
<li><a href="<?php echo $url; ?>" title="<?php echo $title; ?>">
<span><?php echo $title; ?></span>
</a>
</li>
<ul>
<?php if( $caption ): ?>
<p class="wp-caption-text"><?php echo $caption; ?></p>
</div>
<?php endif; ?>
<?php endif; ?>

由于所有字段都是单独设置的,因此不仅仅是遍历相同类型(即仅文件字段(的所有字段的数组的问题。

有几种方法可能适合您:

选项 1. 如果文件的所有字段名称都遵循相同的命名模式并按顺序命名,则可以使用该名称进行循环。

例如,假设您的字段命名为 attachment_1 attachment_5:

$statement = get_field('name_of_your_statement_field');  
//do whatever you need to with $statement
for ($i=1; $i<=5; $i++){
//use the number from the loop to find the file by name
$file = get_field('attachment_'.$i);  
if( $file ){
// display file details as appropriate
}
}

选项 2.如果文件字段名称不遵循相同的模式,则可以遍历字段名称数组。

例:

$statement = get_field('name_of_your_statement_field');
//do whatever you need to with $statement
// Create an array with the field names of all your files
// N.B. This also lets you specify the order to process them
$file_fieldnames = array('file_1', 'file2', 'another_file'); 
foreach ($file_fieldnames as $fieldname) {
$file = get_field($fieldname);
if( $file ){
// display file details as appropriate
}
}

选项 3.如果要遍历帖子/页面上的所有字段,可以将字段保存到数组中。

乍一看,这似乎是最通用的方法,但由于您不知道每个字段的类型而不知道如何处理和显示它们,因此它变得复杂......您首先必须确定它是什么字段类型。您可以按名称(类似于上面(执行此操作,也可以尝试通过检查字段内容来识别每个字段的内容。

请注意,检查字段内容是非常危险的,因为还有其他字段类型可以具有类似的特征(例如,文件不是唯一可以具有 url 的类型(,所以我不建议该策略,除非您 100% 确定您永远不会更改字段组或将另一个字段组添加到帖子/页面。

例:

$fields = get_fields();
foreach ($fields as $fieldname => $content) {
if (is_string ($content)){
// display the string
}
else if (is_array($content) && $content['url']) { 
// then you could assume its a file and display as appropriate
}
}

请注意,不会测试任何代码。但是,它应该让您了解每个选项背后的逻辑,以便您可以决定什么适合您。

基于提供的新代码进行更新:

根据 JSFiddle 中的代码参阅下文。我忽略了文件列表之外的标题,因为它没有意义 - 每个文件都可以有自己的标题。

<?php
for ($i=1; $i<=5; $i++){
//use the number from the loop to find the file by name
$file = get_field('attachment_'.$i);  
if( $file ){
$url = $file['url'];
$title = $file['title'];
$caption = $file['caption'];
// now display this file INSIDE the loop so that each one gets displayed:
?>
<li>
<a href="<?php echo $url; ?>" title="<?php echo $title; ?>" target="_blank">
<span><?php echo $title; ?></span>
</a>
<?php if( $caption ): ?>
<p class="wp-caption-text"><?php echo $caption; ?></p>
<?php endif; ?>
</li>
<?php
}    // end if 
}    // end for loop
?>
<ul>

如果您了解数组,我建议您将文件详细信息添加到数组中,然后执行第二个循环以显示文件...但是我猜你不太精通基本的编码结构,因为你不了解循环,所以我试图保持简单。如果您尝试编写代码,我强烈建议您学习一些有关编程基础知识的教程。

最新更新