• I want to be able to let the person using the website to change the background color on the body element by using my widget.

    In the widget function I find out which RGB color that was chosen.

    The body element looks like this when I used inspect component from chrome browser

    <body class="single single-post postid-115 single-format-standard logged-in admin-bar  customize-support">

    So how do I change background color on the body element to what have been enetered?

    Here is my widget function.

    public function widget( $args, $instance ) {
    		extract( $args );
    		echo $before_widget;
    		$title = apply_filters( 'widget_title', $instance['title'] );
    
    		$color = ( empty ( $instance['color'])) ? ' ' : $instance['color'];
    		echo $before_title . $instance['title'] . $after_title;
    
    		switch($color)
    		{
    		case 'red' :
    		     //Here I want to change background-color on the body element to red
    		   break;
    		case 'green' :
    	  //Here I want to change background-color on the body element to green
    		   break;
    		case 'blue' :
    		 //Here I want to change background-color on the body element to blue
    		   break;
    
    		default :
    		   echo "No color given";
    		}
    
    		echo $after_widget;
    	}
Viewing 1 replies (of 1 total)
  • Moderator Jose Castaneda

    (@jcastaneda)

    THEME COFFEE MONKEY

    Ideally you wouldn’t need to use the switch in the widget function. If it comes to that point then it may sound like you aren’t saving the option(s) right. But if you wanted to change it, you can hook to wp_head and output the style.

    add_action( 'wp_head', 'user_color' );
    function user_color(){
        $color = ( $instance['color'] ) ? $instance['color'] : '';
        echo '<style>';
        echo 'body { background: ' . $color '; }';
        echo '</style>';
    }

    I’m wondering why you want to use a widget to change the body background when core has something already built-in?

Viewing 1 replies (of 1 total)

The topic ‘Change background color from a Widget’ is closed to new replies.