A client of mine has been having trouble placing images on a page of her WordPress site. The page is to have an image (left aligned) with some text on the right, then another image with some text on the right, etc. Unfortunately when the text is shorter than its image, the following image is placed to the right of the first image, which makes the layout quite a jumble.

She's using the visual editor, and has difficulty with the text editor, so adding class="clearfix" (referencing the usual after: clearfix hack[1] in styles.css) to the last paragraph before the succeeding image was not going to work for her.

So I undertook adding a clearfix shortcode for my client's convenience. (Answer to come.)

[1]: Cf. http://css-tricks.com/all-about-floats/, also see http://perishablepress.com/lessons-learned-concerning-the-clearfix-css-hack/

  • 1
    What is your question? Are you having problems implementing a shortcode? – Jared Cobb Jan 9 '13 at 16:14
  • img + p + img{clear:left} didn’t work? – fuxia Jan 9 '13 at 16:18
  • Hi, thanks for your replies. The question is the setup for my own answer. Unfortunately as a new user here, I have to wait 8 hours to answer my own question. I've got it all ready, just need to wait the time out. – JohnK Jan 9 '13 at 16:38
  • @toscho, thanks again for your reply. I suspect it makes a difference that there can and sometimes are multiple ps between imgs. – JohnK Jan 11 '13 at 18:37

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.


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.