0

Apologies if this is a simple question and/or it's nonsensical.

What I'm trying to do is change the output of a string, based on 2 simple variables.

This is the original variable;

$src = 'http://example.org';

And I have the following option variables which pull data from a Wordpress shortcode (If it exists);

$bg = $attr['background'];
$col = $attr['color'];

What I want to achieve is this, if neither of the option variables have values the original variable remains unchanged.

If only one of the option variables exist, the original variable's value becomes;

http://example.org?background='.$bg.'

or

http://example.org?color='.$col.'

Depending on which one has a value.

If both option variables have values, the original value needs to become;

http://example.org?background='.$bg.'&color='.$col.'

Can someone point me in the right direction on this please? It would be greatly appreciated.

3 Answers 3

2

Try this:

$src = 'http://example.org';
$start = '?';

if(isset($attr['background'])) {
    $src .= $start . 'background=' . $attr['background'];
    $start = '&';
}

if(isset($attr['color'])) $src .= $start . 'col=' . $attr['color'];

Should be self-explanatory, but we slowly build up the $src variable depending on whether a background or color is set.

Sign up to request clarification or add additional context in comments.

Comments

2

You can do this easily using the add_query_arg() function built into WordPress.

$url = 'http://example.org';

if ( isset($attr['background']) ) {

    add_query_arg( 'background', $attr['background'], $url );

}

if ( isset($attr['color']) ) {

    add_query_arg( 'color', $attr['color'], $url );

}

Comments

1

Here's a small function that creates the params out of a given parameter-array as you have it:

<?php
// the settings:
$attr = [];
$attr['background'] = "#ededed";
$attr['color'] = "red";
#$attr['otherparam'] = "123456";
$url = 'http://example.org';

// the method
function createParamsString($params) {
    $p = [];
    foreach($params as $key=>$value) { 
       $p[]  = $key."=".urlencode($value);
    }
    return implode("&", $p);
}

// usage:
$paramsString = createParamsString($attr);

$url = !empty($paramsString) ? $url."?".$paramsString : $url;

echo $url;

This way it's modular. You can just add entries to $attr an all is good. urlencode is important if you have a values like #EDEDED for background.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.