Home > Software design >  pass page specific ACF image array values outside of the loop
pass page specific ACF image array values outside of the loop

Time:01-14

I have some ACF(advanced Custom Fields) image values that I display in an include file outside of the main loop. The ACF image is stored as an array, so I would like to display the array values, for example URL, alt tag, size , ect..

This is my code

<?php
global $wp_query;
$postid = $wp_query->post->ID;
$callout_image = get_post_meta($postid, 'callout_image', true);
wp_reset_query();
?>


        <?php if( !empty( $callout_image ) ): ?>
            <img src="<?php echo esc_url($callout_image['url']); ?>" alt="<?php echo esc_attr($callout_image['alt']); ?>" />
        <?php endif; ?>
    

the error is Warning: Illegal string offset 'url' in

What am I doing wrong?

UPDATE: Fixed code

<?php
global $wp_query;
$postid = $wp_query->post->ID;
$callout_image = get_field('callout_image', $postid);
wp_reset_query();
?>


        <?php if( !empty( $callout_image ) ): ?>
            <img src="<?php echo esc_url($callout_image['url']); ?>" alt="<?php echo esc_attr($callout_image['alt']); ?>" />
        <?php endif; ?>
    

CodePudding user response:

If the $callout_image is an array that contains url & alt,

Try this:

<?php if( !empty( $callout_image ) ): ?>
    $url = $callout_image['url'];
    $alt = $callout_image['alt']; 
    <img src="<?php echo esc_url($url); ?>" alt="<?php echo esc_attr($alt); ?>" />
<?php endif; ?>

https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.simple

CodePudding user response:

https://www.advancedcustomfields.com/resources/image/

<?php
$image = get_field('image');
if( $image ):

    // Image variables.
    $url = $image['url'];
    $title = $image['title'];
    $alt = $image['alt'];
    $caption = $image['caption'];

    // Thumbnail size attributes.
    $size = 'thumbnail';
    $thumb = $image['sizes'][ $size ];
    $width = $image['sizes'][ $size . '-width' ];
    $height = $image['sizes'][ $size . '-height' ];

    // Begin caption wrap.
    if( $caption ): ?>
        <div >
    <?php endif; ?>

    <a href="<?php echo esc_url($url); ?>" title="<?php echo esc_attr($title); ?>">
        <img src="<?php echo esc_url($thumb); ?>" alt="<?php echo esc_attr($alt); ?>" />
    </a>

    <?php 
    // End caption wrap.
    if( $caption ): ?>
        <p ><?php echo esc_html($caption); ?></p>
        </div>
    <?php endif; ?>
<?php endif; ?>
  •  Tags:  
  • Related