WordPress use shortcode to render HTML snippet. Shortcode with parameters to render template. Using shortcodes to insert HTML template into editor. Shortcode to render partial template. Shortcode custom template. Shortcode custom html.

Let’s say you want to insert an HTML code like this in your page:

<div class="pure-g">                
	<div class="pure-u-16-24">
		<article class="my-custom-article-class">
			<h1>My Custom Header</h1>
			<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
			<p>Another lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
		</article>
	</div>
</div>

The problem is that you use the same HTML structure all over your pages (even in the same page). The only thing different is header (h1) and text (p) so you want to use shortcode to automate the process.

Here is a function, which you can add to your functions.php file of your current theme:

<?php

/**
 * Shortcode to render template with given arguments (values)
 * 
 * @param array $attr Array of parameters to use to render template-part with given id ($attr['id'])
 * 
 * usage example: [snippet id="1" header="My h1 instead of #header#" text="Text to use instead of #text# placeholder"]
 * (in this case it will look for: template-parts/snippet-1.php)
 * 
 * Template example (let's say it is your-current-theme-path/template-parts/snippet-1.php):
 * <div>
 *   <h1>#header#</h1>
 *   <p>#text#</p>
 * </div>
 */
add_shortcode('snippet', function ($attr) {

    // id must be set to get correct snippet (template-part)!
    if (!is_array($attr) || !isset($attr['id'])) {
        return;
    }
    
    $fileContent = trim(file_get_contents(locate_template("template-parts/snippet-" . $attr['id'] . ".php")));    
    if ($fileContent) {
        // fill placeholders with actual data
        if (is_array($attr)) {
            foreach ($attr as $k => $v) {
                $fileContent = str_replace("#" . $k . "#", $v, $fileContent);
            }
        }
    }
    
    return $fileContent;
});

As documentation on this function says, you can now create your template, let’s say snippet-simplearticle.php (put it to this location: your-current-theme-path/template-parts).
Now you can place your HTML template there:

<div class="pure-g">                
	<div class="pure-u-16-24">
		<article class="my-custom-article-class">
			<h1>#header#</h1>
			<p>#text#</p>
			<p>#text2#
		</article>
	</div>
</div>

And this is how your shortcode (which you can insert into WYSIWYG of the page you are interested in) looks like:

[snippet id="simplearticle" header="Me special header" text="My impressive paragraph" text2="My another paragraph!"]

Done! Hope it helps!

Leave a comment