skip to Main Content

Instead of outputting the Custom fields AFC image field as an regular image, i want it do render as an div with the image as background.

$myImg = get_post_meta( $product->id, 'product_img', true );
    $imgSrc = wp_get_attachment_image_src( $myImg );


    if ( ! empty( $myImg ) ) {
        echo '<div style="background-image: url(<?php echo $imgSrc [0]; ?> );"></div>';
    }

This string does work with my other Custom fields, but doesn’t seems to render anything with the image field.

2

Answers


  1. ACF field usage

    echo '<div style="background-image: url(' . get_field("image_field") . ');">';
    

    WP default method:

    $myImg = get_post_meta( $product->id, 'product_img', true );
       $imgSrc = wp_get_attachment_image_src( $myImg );
    
    
        if ( ! empty( $myImg ) ) {
            echo '<div style="background-image: url('. $imgSrc [0] . ' );"></div>';
        }
    
    Login or Signup to reply.
  2. If you’re inside the product archive loop you can just retrieve and display as such:

    If your image field is set to Image URL:

    <?php $myImg = get_field('product_img');
    if($myImg):?>
        <div style="background-image: url('<?php echo $myImg;>');"></div>
    <?php endif;?>
    

    If your image field is set to Image Object:

    <?php $myImg = get_field('product_img');
    if($myImg):?>
        <div style="background-image: url('<?php echo $myImg['url'];>');"></div>
    <?php endif;?>
    

    There is no need to check if the variable is not empty as using get_field() does that checking for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search