1

I am trying to figure out how to figure out how to check to see if a shortcode attribute is equal something and than if it is set a variable.

I have an image shortcode with an attribute of float and I want to set a class to float right if the user enters in float="right" as an attribute but if not than do nothing.

add_shortcode( 'img', 'img_shortcode' );
function img_shortcode( $atts, $content = null ) {
$atts = shortcode_atts(
array(
    'float' =>'',
), $atts);

$ImgFloat = '';

if(float attribute = right){
        $ImgFloat = 'class="img-right"';
    }

return '
<div class="img-shortcode">
    <img '. $ImgFloat .' src="'. $content .'" />
</div>
';
}

Above is the shortcode, as you can see the If statement is where I'm having the trouble, I would like to figure out how to check to see if the attribute float is set to anything if it is set to right, than make $imgFloat variable equal to the float right class that I have set.

Greenhoe
  • 1,051
  • 4
  • 18
  • 41

2 Answers2

2

Change this:

if(float attribute = right){
        $ImgFloat = 'class="img-right"';
}

To this:

if ( 'right' == $atts['float'] ) {
    $ImgFloat = 'class="img-right"';
}

OK so I may have complicated the answer by flipping the conditional around but it's a good habit to get into :)

The important part is we're saying if $atts['float'], which is the value of float="" in the shortcode, is equal to right then add the class.

shortcode_atts(... at the top of the function is where $atts['float'] is given a default value. If the user doesn't enter float=".. then the value is a blank string.

Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58
0

shortcode_atts returns an array combining the parameters passed in with the defaults you specify. So the float attribute will be stored in $atts['float']

Hobo
  • 7,536
  • 5
  • 40
  • 50
  • So I would use if($atts['float'] = 'right') correct? – Greenhoe Jul 25 '14 at 21:01
  • Use two equals signs (`==`), not one. Two checks for equality, one assigns the value to the variable. What you have there will set `$atts['float']` to 'right', losing the original value, and always executing the code in your `if` block (since PHP will do `if('right')`, and 'right' is "truthy". See http://stackoverflow.com/questions/20275032/php-if-single-or-double-equals and "Converting to boolean" [here](http://php.net/manual/en/language.types.boolean.php)). – Hobo Jul 26 '14 at 05:14
  • 1
    The `==` versus `=` is why in @Nathan Dawson's answer he has `'right' == $atts['float']`, not `$atts['float'] == 'right`. If you accidentally only type one (`'right' = $atts['float']`), PHP will throw an error, since you can't assign a value to a literal. An error's much better than a hard to find bug because of missing `=`. – Hobo Jul 26 '14 at 05:18