Sometimes as I code a page I find it necessary to use some specific html to get the job done. the problem is that when I hand the site over to the client and they start editing in the Visual editor there is a danger that they will inadvertently over-write my html (which isn’t visible in the visual ecitor).
The answer is to use shortcode for html which shows up in the visual editor an kinda’ says “don’t touch”. So what I need is shortcode that is versatile and will produce nested, if necessary html. the code for the answer is below.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | function jma_elements($atts, $content = null){ ob_start(); extract( shortcode_atts( array( 'element' => 'div', 'id' => '', 'class' => 'html_element', 'style' => '', 'interior' => '', ), $atts ) ); $attributes = array('id' => $id, 'class' => $class, 'style' => $style); echo '<'. $element . ' '; foreach($attributes as $name => $attribute){ if($attribute){ echo $name . '="' . $attribute . '" '; } } echo '>'; echo do_shortcode($content); echo '</' . $element . '>'; $x = ob_get_contents(); ob_end_clean(); return $x; } add_shortcode('html','jma_elements'); add_shortcode('html_inner','jma_elements'); add_shortcode('html_inner_inner','jma_elements'); add_shortcode('html_inner_inner_inner','jma_elements'); |
The shortcode by default produces a div the class “html_element”, but this can be over-ridden for instance this shortcode:
0 1 2 | [html element='h2' class='title-class' id='title-id' style='color: red']My Title[/html] |
will produce:
0 1 2 | <h2 id="title-id" class="title-class" style="color: red">My Title</h2> |
I envision this being used for divs (default), spans, paragraph tags and h1, h2 … (image tags and links can be added and shown in the visual editor). This shortcode can also be nested up to four deep by adding “_inner” to each successive level. WordPress will not allow nesting a shortcode within itself see here.