Consider that I wish to display a box with a border and two lines within it using HTML. Here is the code:
<div style="
border: solid;
">
<div>This is some text</div>
<div>This is another line of text</div>
</div>
We can insert it using the "Text" editor on a WordPress page:
Unfortunately, the website does not display as expected. Here is the result.
The screenshot demonstrates that WordPress adds an extra "p>/p>" tag between two divs that was not included in the original code. It may not seem to be much, yet it completely alters the box's appearance. Similarly, you cannot anticipate where WordPress may alter your code.
Do not copy and paste HTML fragments into the post editor.
Solution: Create and Use a Shortcode Instead
How to insert a shortcode into WordPress was one of our earlier article. This is what we will employ here. It entails putting custom code into your functions.php file or a custom PHP plugin. Here is the code that will be used for the HTML excerpt above:
function html_func( $atts, $content = null) {
$html_code = <<<EOT
<div style="
border: solid;
">
<div>This is some text</div>
<div>This is another line of text</div>
</div>
EOT;
return $html_code;
}
add_shortcode( 'html', 'html_func' );
Replace the bolded portion with your clip. A caution. Make certain that the indentation of the last "EOT;" phrase is not altered. The requirements demand that it be on a single line by itself, with no tabs or spaces.
This generates a new shortcode named "html," which is used in the WordPress editor as follows:
Which creates the following output:
As you can see, the extra "p" tag between the div components has been removed, and the code now appears as anticipated! Using a shortcode like this is the optimal method for inserting custom images or HTML code into WordPress.
Adding Parameters to the Shortcode
If you need to modify the HTML for a specific page, attributes may be used as arguments. For instance, suppose we want to modify the HTML's first and second lines. We modify the code as follows:
function html_func( $atts, $content = null) {
$atts = shortcode_atts( array(
'first_line' => 'Sample first line',
'second_line' => 'Sample second line'
), $atts, html);
$first_line = $atts["first_line"];
$second_line = $atts["second_line"];
$html_code = <<<EOT
<div style="
border: solid;
">
<div>$first_line</div>
<div>$second_line</div>
</div>
EOT;
return $html_code;
}
add_shortcode( 'html', 'html_func' );
And now, pass the first and second lines as an argument:
[html first_line = "This is the first line" second_line="This is the second line"]
And this gives us the following output:
As can be seen, we have customised the result. Therefore, you may reuse this design on several pages while still customising it for each occasion! Now, you may integrate any HTML design into WordPress without worrying about its reusability or integrity.