0

I am trying to implement the ability to choose a different body background image to different posts, pages and categories. I am using Advanced Custom Fields to add an image field to every post, page or category. Then I need a way to display the images chosen in this field as body background image.

This is my code so far. I think this approach might work but can't seem to be able to figure out what I am missing..

function my_theme_body_bg_image() {
    global $post;
    // set the handle of the main stylesheet - style.css
    $handle = 'main-styles';
    // set the custom background image field
    $bg_image = get_field('body_background_image');
    $css = "body { background-image: url('$bg_image'); }";
    wp_add_inline_style( $handle, $css );
}
add_action( 'wp_enqueue_scripts', 'my_theme_body_image_bg' );
  • It would be nice when you delete the duplicate you created here – Charles Feb 23 '16 at 21:41
0

You need to add the classes for the corresponding cases.

For pages/posts:

$css = "body.page-id-**post_id** { background-image: url('$bg_image'); }";

For categories:

$css = "body.category-**category_id** { background-image: url('$bg_image'); }";

You can retrieve post_id with $post->ID. For the category you need to check whether the page is_archive() and to append the corresponding ID or category name.

  • Thanks. Is there any way this can be dynamic? A way of getting the current page id for example and then when I am on a category page, post page, or normal page the background image that has been chosen on that pages field is applied to the body of that current page? – Madeirense Feb 24 '16 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.