php - Output just the background color, just an image or both together

147

On my template I have a field where the user(s) can choose and select a background for their site.

enter image description here

This is called from the IDbackground-one in an array.

My question is, how would I be able to output this into the head section of my CSS correctly if the users are only given the following options:

1) The choice of just a background color

background: #990000;

2) The choice of just a background image

background: url(../images/example.jpg) no-repeat top left scroll;

3) Or the choice of a background color and an image

background: #990000 url(../images/example.jpg) no-repeat top left scroll;


This is my current snippet of code to output the script into the css head section:

<?php $background = of_get_option('background-one'); {  
    if ($background['color'] || $background['image']) {
        echo 'body {
        background: ' . $background['color'] . ' url(' . $background['image']. ') ' .$background['repeat']. ' ' .$background['position']. ' ' .$background['attachment']. ';';
    }

    else if ($background['color']) {  
        echo 'body {
        background: ' . $background['color']. ';';
    }

    else if ($background['image']) {
        echo 'body {
        background: ' . 'url(' . $background['image']. ') ' .$background['repeat']. ' ' .$background['position']. ' ' .$background['attachment']. ';';
    };
}
?>

But with that, the results are:

1) The choice of just a background color

background: #990000 url() no-repeat top left scroll;

2) The choice of just a background image

background:url(../images/example.jpg) no-repeat top left scroll;

3) Or the choice of a background color and an image

background: #990000 url(../images/example.jpg) no-repeat top left scroll;

As I'm fairly new to writing PHP, how would I re-work my snippet above to get the results I'm after?

451

Answer

Solution:

Change the following:

if ($background['color'] || $background['image']) {

To this:

if ($background['color'] && $background['image']) {

The reason your snippet doesn't work like you want it to is because "||" equals "OR", which means that if either "$background['color']" or if "$background['image']" is set, the if-statement will apply.

Using "&&" instead, which in English means "AND", would make the if-statement only apply if both "color" and "image" are set.

People are also looking for solutions to the problem: PHP Curl with port number issue

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.