首页 > 解决方案 > 如何在 WordPress 中显示来自自定义字段的多个图像

问题描述

我有一个名为“图像”的自定义字段。我想将此自定义字段显示为图片。我怎样才能做到这一点?

https://prnt.sc/l0eyv3

我写了一个 php 代码,但它只显示 1 张图像,它没有显示任何其他图像。

我的代码:

<?php $images = get_post_meta(get_the_ID(), 'images', true); ?>
<?php if ( $images && is_single() ): ?>
<?php
    $images = get_post_meta( $post->ID, 'images' );
    if ( $images ) {
        foreach ( $images as $attachment_id ) {
            $thumb = wp_get_attachment_image( $attachment_id, 'full' );
            $full_size = wp_get_attachment_url($attachment_id);
            printf( '<a href="%s">%s</a>', $full_size, $thumb );
        }
    }
?></br>
<?php endif; ?>

标签: phpwordpresscustom-fields

解决方案


这应该有效。解释见评论。

<?php
$images = get_post_meta(get_the_ID(), 'images', true);
if ( $images && is_single() ):
    $images = get_post_meta( $post->ID, 'images' );

    if ( $images ) {
        //you can't loop through strings, you need to convert the string to an array
        $images = explode( ",", $images );

        foreach ( $images as $attachment_id ) {
            $thumb = wp_get_attachment_image( intval($attachment_id), 'full' );
            $full_size = wp_get_attachment_url($attachment_id);
            printf( '<a href="%s">%s</a>', $full_size, $thumb );
        }
    }
    echo '<br>';
endif;
?>

推荐阅读