Halloween Sale 15% off Ends in See the plans
PHP

Text Size Buttons Shortcode

Adds a [text_size_controls] shortcode with "A-", "A" and "A+" buttons that make the whole site's text smaller or larger for that visitor, remembered on their device.

Don’t have WPIDE yet? Install it on your site

Code

// Scaling steps in percent of the browser's default font size.
$wpide_text_steps = array( 90, 100, 112, 125, 140 );

add_shortcode( 'text_size_controls', function () use ( $wpide_text_steps ) {
    static $printed = false;

    $html = '<div class="wpide-textsize" role="group" aria-label="Text size">'
        . '<button type="button" data-step="-1" aria-label="Smaller text">A−</button>'
        . '<button type="button" data-step="0" aria-label="Default text size">A</button>'
        . '<button type="button" data-step="1" aria-label="Larger text">A+</button>'
        . '</div>';

    if ( ! $printed ) {
        $printed = true;
        $html   .= '<style>.wpide-textsize{display:inline-flex;gap:4px}.wpide-textsize button{min-width:44px;min-height:44px;font-weight:700;cursor:pointer}</style>';
        $html   .= '<script>(function(){var steps=' . wp_json_encode( array_values( $wpide_text_steps ) ) . ',key="wpideTextStep",def=steps.indexOf(100),i=def;try{var s=parseInt(localStorage.getItem(key),10);if(!isNaN(s)&&steps[s]){i=s;}}catch(e){}function apply(){document.documentElement.style.fontSize=steps[i]===100?"":steps[i]+"%";try{localStorage.setItem(key,i);}catch(e){}}apply();document.addEventListener("click",function(e){var b=e.target.closest(".wpide-textsize button");if(!b){return;}var d=parseInt(b.getAttribute("data-step"),10);i=d===0?def:Math.max(0,Math.min(steps.length-1,i+d));apply();});})();</script>';
    }

    return $html;
} );

Notes

Works best with themes that size text in rem or em; pixel-based themes only scale partly.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.