WordPress: assegnare uno sfondo custom a qualsiasi elemento

WordPress: assegnare uno sfondo custom a qualsiasi elemento

WordPress permette di aggiungere un'immagine di sfondo personalizzata (custom) solo per l'elemento body. Tuttavia, possiamo cambiare questa impostazione predefinita utilizzando una nostra funzione di callback. Vediamo come fare.

L'unica verifica da fare riguarda la versione di WordPress in uso. Dalla 3.4, infatti, la funzione di callback va inserita nel parametro wp-head-callback dell'array di opzioni della funzione add_theme_support.

Possiamo includere il seguente codice nel file functions.php, cambiando solo il selettore CSS #header con quello dell'elemento scelto da voi:


<?php
function my_change_custom_background() {
	$background = get_background_image();
	$color = get_background_color();

	if ( ! $background && ! $color )
		return;

	$style = $color ? "background-color: #$color;" : '';

	if ( $background ) {
		$image = " background-image: url('$background');";

		$repeat = get_theme_mod( 'background_repeat', 'repeat' );

		if ( ! in_array( $repeat, array( 'no-repeat', 'repeat-x', 'repeat-y', 'repeat' ) ) )
			$repeat = 'repeat';

		$repeat = " background-repeat: $repeat;";

		$position = get_theme_mod( 'background_position_x', 'left' );

		if ( ! in_array( $position, array( 'center', 'right', 'left' ) ) )
			$position = 'left';

		$position = " background-position: top $position;";

		$attachment = get_theme_mod( 'background_attachment', 'scroll' );

		if ( ! in_array( $attachment, array( 'fixed', 'scroll' ) ) )
			$attachment = 'scroll';

		$attachment = " background-attachment: $attachment;";

		$style .= $image . $repeat . $position . $attachment;
	}
?>
<style type="text/css">
#header { <?php echo trim( $style ); ?> }
</style>
<?php
}
if ( is_wp_version( '3.4' ) ) {
	add_theme_support( 'custom-background', array( 'wp-head-callback', 'my_change_custom_background' ) );
}
else {
	add_custom_background('my_change_custom_background');
}
?>
Torna su