I am using Sage Theme.
I have an inline body background image in base.php which grabs an image from a custom field in the page
if ( get_field('banner_image') ) {
$img = get_field('banner_image');
echo 'style="background-image: url(\'' . $img . '\');"';
}
For certain templates (single-$posttype.php for example) I would like to override this background image with one from the options page.
$img = get_field('default_posttype_banner', 'option');
Currently I am using conditionals in the base.php such as
if (is_tax( 'taxonamy-term', 'my-term' )) {
$img = get_field('my_term_banner', 'option');
}
else if (get_post_type( get_the_ID() ) == 'my-custom-post-type') {
$img = get_field('my_post_type_banner', 'option');
}
Is there a better/more reliable way to do this that ideally would allow me to override the background image from any template without having to edit the base.php conditionals each time?
You can use an acf/load_value filter https://www.advancedcustomfields.com/resources/acf-load_value/.
add_filter('acf/load_value/name=banner_image', 'override_banner_image', 10, 3);
function override_banner_image($value, $post_id, $field) {
if ($some_condition) {
// do conditionals and set value to a different attachment ID
}
return $value;
}
You’d still need to add to this function whenever you wanted to add more conditions to it.