A shortcode is a small tag in square brackets that the editor replaces with dynamic content. Register one with add_shortcode() and always return the output instead of printing it.

Shortcode with attributes and content

function lotgrafix_button_shortcode( $atts, $content = null ) {
    $atts = shortcode_atts( array(
        'url'   => '#',
        'color' => '#ff4500',
    ), $atts, 'lotgrafix_button' );

    return sprintf(
        '<a class="lotgrafix-button" style="background:%1$s" href="%2$s">%3$s</a>',
        esc_attr( $atts['color'] ),
        esc_url( $atts['url'] ),
        esc_html( $content )
    );
}
add_shortcode( 'lotgrafix_button', 'lotgrafix_button_shortcode' );

How to use it

Type this inside a post, a page or a Shortcode block.

[lotgrafix_button url="https://example.com" color="#0073aa"]Buy now[/lotgrafix_button]

Use a shortcode inside a PHP template

echo do_shortcode( '[lotgrafix_button url="https://example.com"]Buy now[/lotgrafix_button]' );

Shortcode with complex HTML output

When the output has a loop or many lines, use output buffering so you can write normal PHP and HTML and still return a string.

function lotgrafix_recent_posts_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'count' => 3,
    ), $atts, 'lotgrafix_recent' );

    $lotgrafix_query = new WP_Query( array(
        'posts_per_page' => absint( $atts['count'] ),
    ) );

    ob_start();

    if ( $lotgrafix_query->have_posts() ) {
        echo '<ul class="lotgrafix-recent">';
        while ( $lotgrafix_query->have_posts() ) {
            $lotgrafix_query->the_post();
            echo '<li><a href="' . esc_url( get_permalink() ) . '">' . esc_html( get_the_title() ) . '</a></li>';
        }
        echo '</ul>';
        wp_reset_postdata();
    }

    return ob_get_clean();
}
add_shortcode( 'lotgrafix_recent', 'lotgrafix_recent_posts_shortcode' );

Usage: [lotgrafix_recent count="5"]

Rules to remember

  • Always return the content. If you echo it, the output appears at the top of the page.
  • Attribute names are lowercase.
  • Escape every value you print and sanitize every attribute you receive.
«
»