Here is my shortcode
function feature_shortcode( $atts, $content ) {
$atts = shortcode_atts( array(
'main_content' => !empty($content) ? $content : "Add a feature.",
'width' => '',
'screen' => array(
'large' => 'col-lg',
'medium' => 'col-md',
'small' => 'col-sm',
'smaller' => 'col-xs',),
'class' => ' feature',
'icon' => '',
'link' => '',
'title' => ''
), $atts );
extract($atts);
return '<div class="'. $screen.$width.$class .'">
<span class="round"><i class="fa fa-'. $icon .'"></i></span>
<h4>'. $title .'</h4>
<p>'. $main_content .'
<a href="'. $link .'">
learn more <i class="fa fa-long-arrow-right">
</i></a></p></div>';
}
add_shortcode( 'feature', 'feature_shortcode' );
Here is the shortcode in action
[feature screen="medium" width="3" icon="moon-o" title="Creative" link="https://codex.wordpress.org/Shortcode_API"]Lorem ipsum eu suspendisse, sem curabitur elit malesuada.
[/feature]
It returns
<div class="medium3 feature"> else is working fine.....</div>
But I want to return “col-md-” while using ‘medium’ as screen key. That should generate
<div class="col-md-3 feature"> else is working fine.....</div>
what should I do if I want to return
<div class="col-sm-3 col-md-3 feature"> else is working fine.....</div>
First, decide how you want your user to list multiple screen and width values.
For example you may want them to be listed sequentially, separated by spaces, and matching pairs of screen and width values in order of appearance, or fallback to some default width.
could generate:
where the default
width
is3
.Next, as per Harsh Pandya’s suggestion, create an array that maps all screen values to the respective Bootstrap classes.
Then in your
feature_shortcode
function, use explode to extract the individual user-supplied values from the screen and width attributes and store them in arrays.$user_screens
and$user_widths
will look likeand
Next, iterate through the user-supplied
screen
values. For each value, append a matching class to your final output. Also, if there is a matchingwidth
value – append it; otherwise, fallback to some default width.Finally, return the $boostrap_class in your output:
Here is the complete solution:
If you are giving values to screen parameter then it will replace the default array with that value so make changes in your code like this.