获取图像大小高级自定义字段

Get Image Size Advanced Custom Fields

我正在尝试使用高级自定义字段获取带有附件大小的图像 URL。该字段设置为 ID。我已经使用这种方法通过 ID 毫无问题地获取其他图像。然而,这并没有拉出渲染图像。它正在提取 ID 号并将其显示在页面上。我难住了...

<?php
$the_query = new WP_Query( array(
    'post_type' => 'listicles',
    'tax_query' => array(
        array (
        'taxonomy' => 'visibility',
        'field'    => 'slug',
        'terms' => 'listicles-resortsvisible',
        ),
    ),
) ); 
    $listicleimage = the_field('listicle_featured_image', $post->ID);
    $listicleimgsize = 'listicle-thumb';
    $listicleimg_array = wp_get_attachment_image_src($listicleimage, $listicleimgsize);
    $listicleimg_url = $listicleimg_array[0];
?>

<ul
class="row small-up-1 medium-up-2">

<?php if ( $the_query->have_posts() ) : ?>

<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>


<li class="small-12 medium-6 column">


<img
    src="<?php echo  $listicleimg_url; ?>"
    class="align-center" />

//THE REST OF MY CONTENT//

</li>
<?php endwhile;?>
<?php endif; ?>
</ul>

<?php wp_reset_query(); ?>

您应该使用 wp_get_attachment_image 而不是 wp_get_attachment_image_src

wp_get_attachment_image 接受 ID 作为参数。

来源:https://developer.wordpress.org/reference/functions/wp_get_attachment_image/

将此添加到 functions.php

function img_by_id($id, $size, $url) {
        $the_img = wp_get_attachment_image($id, $size);
        if ($url != true) {
            return $the_img;
        }
        else {
            $img_src = get_attr($the_img, 'src');
            return $img_src;
        }
    }

function get_attr($html, $attr) {
    $pc = explode($attr.'="', $html);
    $pc2 = explode('"', $pc[1]);
    return $pc2[0];
}

然后

<?php
    $the_query = new WP_Query( array(
        'post_type' => 'listicles',
        'tax_query' => array(
            array (
            'taxonomy' => 'visibility',
            'field'    => 'slug',
            'terms' => 'listicles-resortsvisible',
            ),
        ),
    ) ); 
    $listicleimage = the_field('listicle_featured_image', $post->ID);
    $listicleimg_url = img_by_id( $listicleimage, 'listicle-thumb', true);

?>

如果您需要尺寸为 $img = img_by_id( $listicleimage, 'listicle-thumb', false) 的完整图像属性; 如果您需要来自 html 标签的特定属性 $attr = get_attr($html, $attr);

我的空白 WP 主题模板上有这个。

你只需要改变

the_field('listicle_featured_image', $post->ID);

get_field('listicle_featured_image', $post->ID);