Site logo

Archived topic

Can I use an image from an Advance Custom Field for my header background?

9 replies · Started by Melissa on April 13, 2019

Viewing posts 1–10 of 10

I need to use a different for the featured image used in blog grids and the hero image on the blog post page. I can create a "hero image" ACF, but how could I use that as an option in my header Element background?

Thanks!

Hi there,

You can do something like this:

add_filter( 'generate_page_hero_background_image_url', function( $url ) {
    $background_image = get_post_meta( get_the_ID(), 'your_custom_field', true );

    if ( $background_image ) {
        $url = $background_image;
    }

    return $url;
} );

Just updated your_custom_field with the name of your custom field.

Let me know :)

Should that give me the option in the drop-down menu on the edit header element page?

I added your filter with "Code Snippets" and can't see any obvious effect. Was that the wrong place to add it?

No, that should automatically use a different background image URL if it's set as a custom field.

For example, if you have a Header applied to the "About" page, and the About page has a custom field with a URL in it, it would use that URL.

Let me know if that's not what you were after :)

Ok, I've got it working nicely now. The problem seems to be that I was using the custom field type "image" not URL.

Thanks so much!

You're welcome :)

Neat! Works for Elements' Header.
Tom, can you give us a solution for .inside-article (or any other container addressed by a class or id), please?

Hi there,

something like this hooked into the WP_head :

<?php
$background_image = get_post_meta( get_the_ID(), 'your_custom_field', true );

if ( $background_image && is_single() ) {
    echo '<style>
    .inside-article {
        background-image: url("' . $background_image . '");
    }';
}

?>

Thank you, David!!
I've used Elements' Hook, chosen Display Rules, and to push it to the wp_head needed to cut off the check if is_single().
Closing tag </style> was missed.
This works for me:

<?php
$background_image = get_post_meta( get_the_ID(), 'my_custom_field', true );

if ( $background_image ) {
echo '
<style id="my-id" type="text/css">
	.inside-article {
		background-image: url("' . $background_image . '");
	}
</style>
';
}
?>

Ooops - thanks for updating an glad you got it resolved.

This archived topic is closed to new replies.