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

时间:2016-08-30 09:17:12

标签: wordpress advanced-custom-fields image-size imageurl

我正在尝试使用高级自定义字段获取带附件大小的图片网址。该字段设置为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(); ?>

3 个答案:

答案 0 :(得分:0)

您应该使用wp_get_attachment_image而不是wp_get_attachment_image_src

wp_get_attachment_image接受ID作为参数。

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

答案 1 :(得分:0)

将此添加到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主题模板上有这个。

答案 2 :(得分:0)

您只需要更改

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

get_field('listicle_featured_image', $post->ID);
相关问题