Here’s the code to be added to functions.php
. As a bonus I’ve included a shortcode for a horizontal rule <hr>
:
function shortcode_hr() {
return '<hr>';
}
function shortcode_clearfix() {
return '<div style="display: block; visibility: hidden; clear: both; height: 0;"></div>';
}
function register_shortcodes() {
add_shortcode('hr', 'shortcode_hr');
add_shortcode('clearfix', 'shortcode_clearfix');
}
add_action( 'init', 'register_shortcodes');
Nothing complicated here, so it’s no surprise that it works as intended.
Explanation:
Function add_action()
sets a hook before the page is loaded (i.e., on init
) to register the given shortcodes via function register_shortcodes()
. The latter adds the shortcode clearfix
to the list of registered shortcodes so that wherever [clearfix]
appears in a post or page it’s replaced by the text returned by function shortcode_clearfix()
. The latter simply returns the shortcode for a clearfix div
. The HTML might not be pretty, but it gets the job done. Pretty straightforward.