如何在高级自定义字段 wordpress post 中获取图像 url

how to get image url in advanced custom field wordpress post

我创建了一个名为 "albums" 的自定义 post 类型。我的每个 post 中都有 5 个自定义字段。 3 个文本字段、1 个图像字段和 1 个文件上传字段。我在模板页面中正确获取了 3 个文本值。但我无法获取图像和文件上传字段的 url 部分。 这是我的代码:

<?php

$posts = get_posts(array(
'post_type' => 'albums'
));

if($posts)
{
echo '<ul>';

foreach($posts as $post)
{
    echo '<li><a href="' . get_permalink($post->ID) . '">' . get_the_title($post->ID) . '</a></li>';
         the_field('album_category'); echo "<br>";
          the_field('album_name'); echo "<br>";
           the_field('slide_name'); echo "<br>";
            the_field('slide_description'); echo "<br>";
            the_field('audio_file'); echo "<br>";
}

echo '</ul>';
}

?> 

这是我当前的输出

Cuckoo-1
Birds
Cuckoo
66, , 2668245306_027a56fe50_b, , , image/jpeg, http://localhost/YIB/wordpress/wp-content/uploads/2016/03/2668245306_027a56fe50_b-1.jpg, 1024, 768, Array
sample sample sample sample sample sample sample
18, , eudynamys-scolopacea, , "eudynamys-scolopacea"., audio/mpeg, http://localhost/YIB/wordpress/wp-content/uploads/2016/03/eudynamys-scolopacea.mp3

试试这个

    <?php
    $imgurl = get_field('slide_image',$post->ID);

    if (filter_var($imgurl, FILTER_VALIDATE_URL) === FALSE)
    {
      $imgurl = wp_get_attachment_url($imgurl);
    }
       echo '<img src="' . $imgurl . '" alt="image">';
    ?>

试试这个。

图像字段和文件字段正在返回数组,因此

$image_m =  get_field('slide_description');
$image_a = get_field('audio_file');
echo '<pre>';
print_r($image_m);
print_r($image_a);
echo '</pre>';

假设你得到的输出是

array(
 ['name'] => 'test';
 ['url'] => 'http://example.mp3';

)

然后写<?php echo $image_m['url'];?>而不是<?php the_field('audio_file');?>

上传到媒体库的图像、视频或文件等媒体的自定义字段以数组形式保存为元数据。您可以尝试这个简单的函数来从自定义字段的元数据中提取 URL 值。此函数在检测到元值中的有效 URL 时遍历数组和 return URL 元值。

将此功能添加到您的 functions.php

function get_post_asset_url($postid, $slug) {
  $meta_array = get_post_meta($postid, $slug, true);
  foreach ($meta_array as $meta) { 
    if (filter_var($meta, FILTER_VALIDATE_URL)){ return $meta; } 
  } 
}

在您的模板中,在“echo”语句中调用此函数:

echo get_post_asset_url($post->ID, "your_asset_field_name");

因此,例如在图像字段上:

<img src="<?php echo get_post_asset_url($post->ID, "image_field_1"); ?>" width="100" height="100">