Subtle diagonal pinstripe pattern in light grey and cream, giving an impression of printed editorial paper

Build a flexible WordPress shortcode plugin

A WordPress shortcode gives editors a compact way to publish a reusable feature without editing theme templates. A plugin registering [content_cards] can let a page choose a category, limit the number of posts, set columns, show excerpts and change button text. Each choice is an attribute, so one template can serve news, property updates or member content.

This guide builds the plugin with secure attribute parsing, escaped output, accessible markup and stylesheet loading. The examples suit Australian businesses, where .com.au sites commonly sell in AUD, WooCommerce stores must account for GST, and development teams from Melbourne to Brisbane often need dependable hosting and support.

Define the shortcode contract

Start with the editor contract rather than the visual design. Document each supported attribute, its accepted values and its default. A typical usage might look like this:

[content_cards category="updates" posts_per_page="6" columns="3" show_excerpt="true" button_text="Read more"]

The shortcode can appear in posts, pages, widgets or reusable blocks. Keeping it independent of a particular theme makes it easier to use across a property website in Sydney and an online shop based in Adelaide.

Create a plugin folder containing a main PHP file, an assets directory and a languages directory. The main file needs a valid plugin header so WordPress can identify it:

<?php
/**
 * Plugin Name: Flexible Content Cards
 * Description: Displays post cards through a configurable shortcode.
 * Version: 1.0.0
 * Requires at least: 6.0
 * Requires PHP: 7.4
 * Text Domain: flexible-content-blocks
 */
defined( 'ABSPATH' ) || exit;

Use a unique prefix such as fcb for functions to avoid clashes with another plugin. Australian English often uses “sanitise” and “localise” in editorial copy, although WordPress API names such as sanitize_key retain their original spelling.

Register the shortcode in WordPress

Register the shortcode during WordPress initialisation. This ensures the core shortcode API is available and avoids problems if another plugin modifies shortcode handling.

function fcb_register_shortcode() {
    add_shortcode( 'content_cards', 'fcb_render_content_cards' );
}
add_action( 'init', 'fcb_register_shortcode' );

The callback receives the supplied attributes, any enclosed content and the shortcode tag. This example uses only attributes, but accepting all three parameters makes the callback flexible if the plugin later supports wrapping content.

Treat the shortcode name as a stable public API. Renaming it from content_cards to content_grid would break existing content, so add a new name and provide a compatibility alias if necessary. The same principle applies to attribute names: accepting posts_per_page now makes it safer to add options later without forcing editors to rewrite every block.

Shortcode callbacks run while WordPress is rendering page content. They should return HTML rather than echo it directly, because output buffering and filters rely on predictable return values. This also keeps database queries, markup generation and escaping separate enough to test each part.

Parse and sanitise attributes

Shortcode attributes normally arrive as strings, so convert them to the expected types and enforce sensible limits. shortcode_atts() supplies defaults and prevents unrecognised attributes from being processed.

function fcb_get_settings( $atts ) {
    $atts = shortcode_atts(
        array(
            'category'       => '',
            'posts_per_page' => 3,
            'columns'        => 3,
            'show_excerpt'   => 'false',
            'button_text'    => __( 'Read more', 'flexible-content-blocks' ),
            'link_url'       => '',
        ),
        $atts,
        'content_cards'
    );

    return array(
        'category'       => sanitize_key( $atts['category'] ),
        'posts_per_page' => min( max( absint( $atts['posts_per_page'] ), 1 ), 12 ),
        'columns'        => min( max( absint( $atts['columns'] ), 1 ), 4 ),
        'show_excerpt'   => filter_var( $atts['show_excerpt'], FILTER_VALIDATE_BOOLEAN ),
        'button_text'    => sanitize_text_field( $atts['button_text'] ),
        'link_url'       => esc_url_raw( $atts['link_url'], array( 'http', 'https' ) ),
    );
}

Integer attributes need upper as well as lower limits. Without them, an editor could accidentally request hundreds of posts and slow the page. Boolean values should accept predictable forms such as true, false, 1 and 0, rather than treating every non-empty string as true.

When a card needs an editor-supplied destination, pass it through esc_url_raw() with an HTTP and HTTPS protocol allowlist. A real destination such as the slot machine tournament page can help check URL handling during testing, but it should not ship as default content. Never build a query directly from an unsanitised attribute.

Render cards and load styles

Use WP_Query to retrieve the requested posts, then escape every value as it enters the markup. Output buffering provides a convenient way to assemble the card grid without scattering echo statements throughout the callback.

function fcb_render_content_cards( $atts ) {
    $settings = fcb_get_settings( $atts );
    $args = array(
        'post_type'           => 'post',
        'post_status'         => 'publish',
        'posts_per_page'      => $settings['posts_per_page'],
        'no_found_rows'       => true,
        'ignore_sticky_posts' => true,
    );

    if ( $settings['category'] ) {
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => $settings['category'],
            ),
        );
    }

    $query = new WP_Query( $args );
    if ( ! $query->have_posts() ) {
        return '';
    }

    ob_start();
    echo '<div class="fcb-grid fcb-grid--' . esc_attr( (string) $settings['columns'] ) . '">';

    while ( $query->have_posts() ) {
        $query->the_post();
        $post_id = get_the_ID();
        $title = get_the_title( $post_id );
        $url = $settings['link_url'] ?: get_permalink( $post_id );
        $excerpt = wp_trim_words( wp_strip_all_tags( get_the_excerpt( $post_id ) ), 24, '…' );

        echo '<article class="fcb-card">';
        echo '<h3 class="fcb-card__title"><a href="' . esc_url( $url ) . '">' . esc_html( $title ) . '</a></h3>';

        if ( $settings['show_excerpt'] ) {
            echo '<p class="fcb-card__excerpt">' . esc_html( $excerpt ) . '</p>';
        }

        printf(
            '<a class="fcb-card__link" href="%1$s" aria-label="%2$s">%3$s</a>',
            esc_url( $url ),
            esc_attr( sprintf( __( '%1$s: %2$s', 'flexible-content-blocks' ), $settings['button_text'], $title ) ),
            esc_html( $settings['button_text'] )
        );

        echo '</article>';
    }

    echo '</div>';
    wp_reset_postdata();

    return ob_get_clean();
}

The fixed h3 should match the surrounding document structure; change it to h2 when the shortcode appears below a page-level heading. An accessible link name should identify its destination, so the example includes the post title in the aria-label. Decorative images should use empty alternative text, while informative images need meaningful descriptions.

Load the card stylesheet through WordPress so browsers can cache it and site owners can override it with their own CSS:

function fcb_enqueue_styles() {
    wp_enqueue_style(
        'fcb-cards',
        plugins_url( 'assets/cards.css', __FILE__ ),
        array(),
        '1.0.0'
    );
}
add_action( 'wp_enqueue_scripts', 'fcb_enqueue_styles' );

The stylesheet can use modifier classes for different column counts and collapse the grid to one column on narrow screens:

.fcb-grid { display: grid; gap: 1.5rem; grid-template-columns: repeat(3, minmax(0, 1fr)); }
.fcb-grid--1 { grid-template-columns: minmax(0, 1fr); }
.fcb-grid--2 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.fcb-grid--4 { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.fcb-card__link { display: inline-block; margin-top: 1rem; }
@media (max-width: 700px) {
    .fcb-grid { grid-template-columns: 1fr; }
}

Extend the plugin for real projects

A shortcode runs during page rendering, so several copies on one page can create several database queries. Cache identical query results where the hosting plan supports a persistent object cache. A short-lived transient is another option, but the cache key must include the query arguments, site language and plugin version. Cached post identifiers remain more flexible than cached HTML when display rules may change.

Provide stable extension points rather than asking other developers to replace the callback. A filter can adjust settings before the query, while another can adjust the final markup. Document every filter argument and continue escaping all plugin-generated output. Sites can then add a badge, custom field or different card template without maintaining a fork of the whole plugin.

If configuration moves into an administration screen, protect it with the manage_options capability and a nonce. Validate the nonce with check_admin_referer() and sanitise submitted values on the server. This reflects the Australian Cyber Security Centre’s emphasis on least privilege, regular patching and safe administrative processes. Authentication checks belong on the handler as well as the menu page.

A WooCommerce variation can query products instead of posts and use functions such as wc_get_product(). Keep prices in AUD and respect the store’s GST display settings instead of calculating tax inside the shortcode. Localise visible strings with translation functions, load the plugin text domain and remember that eastern Australian sites may need dates in AEST or AEDT during daylight-saving changes.

Test, release and maintain the plugin

Test every supported attribute with valid, missing, empty and invalid values. Include excessive column counts, boolean spellings, unknown categories and a query that returns no posts. Attempt script injection through titles, excerpts, button text and URLs to confirm that each value is escaped. Keyboard navigation, focus states and screen-reader labels need checking alongside the visual design.

Use WP_DEBUG during development and inspect database queries with a tool such as Query Monitor. Automated tests can call the settings helper and verify its boundaries, while integration tests can parse a rendered page for the expected number of cards. Test on current and older supported PHP versions, then repeat the release process on a staging copy of the production site.

Give the plugin a semantic version, maintain a changelog and keep backward compatibility for established shortcode attributes. Asset versions should change when CSS or JavaScript changes so browsers receive the latest files. Store the plugin in a controlled repository, use deployment tools where available and record which WordPress and PHP versions each release supports. Regular backups, support contacts and a documented rollback method keep updates manageable for small Australian businesses as well as larger agencies.