How to add background image dynamically in WordPress1 min read

wordpress

add this code to your wordpress function.php file

// Output style
function print_theme_extra_styles() {
  global $post;
  $bg = get_post_meta( $post->ID, 'background', true );
  if( $bg ) :
  ?>
    <style type="text/css">
      .example-class { background-image: url(<?php echo $bg;?>); }
    </style>
  <?php
  endif;
}
add_action( 'wp_print_styles', 'print_theme_extra_styles' );

and add .example-class to your element where you want to add the background