ACF Header Background

2019-09-08 03:23发布

I am using Advanced Custom Fields to display a background image in my header. Now I want to display a default image if there is no ACF-image defined. I tried this code, but it didn't work (image only shows if it is set):

<?php wp_head(); ?>

    <?php if(get_field('header')) {
        $image = get_field('header');
    } else {
       $image = '<img src="#absolute-path-to-my-image">';
    }      
    ?>

    <style type="text/css">
         #inner-header{
             background-image: url('<?php echo $image['url']; ?>');
             background-position:center;
             background-repeat:no-repeat;
             background-size:cover;
         }
    </style>

thanks for any help.

1条回答
疯言疯语
2楼-- · 2019-09-08 04:26

I'd change things up a bit. You're experiencing problems because you're passing an image element in if there's no 'header' present (you should only be passing the src):

<?php
    // Get the field
    $image = get_field('header');
    // Does the field exist ? src : default
    $image_src = $image ? $image['url'] : 'http://example.com/default/src.jpg';
?>

<style>
    #inner-header {
        background: url(<?php echo $image_src; ?>) center / cover no-repeat;
    }
</style>
查看更多
登录 后发表回答