Always Return Output
Shortcode callbacks should return output instead of echoing it. Use output buffering for HTML-heavy templates.
Build WordPress shortcodes visually with custom attributes, defaults, usage previews, and production-ready PHP output.
[cta-button text="Click Here" url="#" style="primary" target="_self"]<?php
/**
* Shortcode: [cta-button]
* Render a call-to-action button.
*
* Usage: [cta-button text="Click Here" url="#" style="primary" target="_self"]
* Add to functions.php or a plugin file.
*/
function cta_button_shortcode( $atts ) {
$atts = shortcode_atts(
[
'text' => 'Click Here',
'url' => '#',
'style' => 'primary',
'target' => '_self',
],
$atts,
'cta-button'
);
// Sanitize shortcode attributes
$text = sanitize_text_field( $atts['text'] );
$url = esc_url( $atts['url'] );
$style = sanitize_text_field( $atts['style'] );
$target = sanitize_text_field( $atts['target'] );
ob_start();
?>
<div class="cta-button-wrapper">
<!-- $text available here -->
<!-- $url available here -->
<!-- $style available here -->
<!-- $target available here -->
<p>Shortcode output goes here.</p>
</div>
<?php
return ob_get_clean();
}
add_shortcode( 'cta-button', 'cta_button_shortcode' );
// To use in PHP templates:
// echo do_shortcode( '[cta-button text="Click Here" url="#" style="primary" target="_self"]' );Shortcode callbacks should return output instead of echoing it. Use output buffering for HTML-heavy templates.
Sanitize all shortcode attributes before rendering them, especially URLs, numbers, and user-entered text values.
For query-based shortcodes, transient caching can reduce repeated database work on busy pages.