Back to Main Site

Creating Custom Shortcodes in PolyCMS for RISE CRM

Last updated on Nov 22, 2026 7:37 AM 7:37 AM 2,020.06 ms

Shortcodes in PolyCMS for RISE CRM let content editors embed dynamic UI components such as call-to-action cards, FAQ accordions, and live post lists inside TinyMCE posts or pages using simple bracket syntax without writing raw HTML. Powered by Libraries/Blog_shortcode.php, the shortcode engine exposes polycms_register_shortcode(), polycms_unregister_shortcode(), polycms_do_shortcode(), and Blog_shortcode::parse_attributes() so plugins and themes can register clean, XSS-safe components in minutes.

Built-In Shortcodes and Core API

PolyCMS ships with three built-in shortcodes located in plugins/polycms/shortcodes/: [polycms_post], [polycms_category], and [polycms_tag]. All built-in and custom shortcodes share the same core API defined in Helpers/polycms_template_helper.php and Libraries/Blog_shortcode.php:

Function / Method Signature Purpose
polycms_register_shortcode() polycms_register_shortcode(string $tag, callable $callback): bool Registers a shortcode handler callback for [tag]
polycms_unregister_shortcode() polycms_unregister_shortcode(string $tag): bool Unregisters an existing shortcode tag
polycms_do_shortcode() polycms_do_shortcode(string $content): string Parses and executes all registered shortcodes within a string
shortcode_atts() shortcode_atts(array $pairs, array $atts): array Merges editor-provided attributes with safe default values
Blog_shortcode::parse_attributes() Blog_shortcode::parse_attributes(string $text): array Parses key="value" pairs and auto-casts booleans (true, false, yes, no, 1, 0, on, off) and numeric strings to int
Blog_shortcode::exists() Blog_shortcode::exists(string $tag): bool Checks whether a shortcode tag is currently registered
Blog_shortcode::strip_shortcodes() Blog_shortcode::strip_shortcodes(string $content): string Removes all shortcode tags (useful for clean plain-text excerpts)

Registering a Self-Closing Shortcode

Register custom shortcodes inside your sub-plugin's main PHP file under plugins/polycms/plugins/{slug}/{slug}.php or inside your active theme's functions.php. Each callback receives ($atts, $content = '', $tag = '') and returns an HTML string.

<?php
defined('BASEPATH') or exit('No direct script access allowed');

polycms_register_shortcode('my_cta', function ($atts, $content = '', $tag = '') {
    $atts = shortcode_atts([
        'text'  => 'Learn More',
        'url'   => '#',
        'color' => 'primary',
    ], $atts);

    // Whitelist allowed button styles
    $allowed_colors = ['primary', 'secondary', 'success', 'dark'];
    $color = in_array((string) $atts['color'], $allowed_colors, true) ? (string) $atts['color'] : 'primary';

    // Allow only relative paths or http(s) URLs to prevent javascript: XSS
    $url = trim((string) $atts['url']);
    if ($url !== '#' && !preg_match('#^(/|https?://)#i', $url)) {
        $url = '#';
    }

    return '<div class="cta-block my-4">'
        . '<a href="' . esc_attr($url) . '" class="btn btn-' . esc_attr($color) . '">'
        . html_escape((string) $atts['text'])
        . '</a>'
        . '</div>';
});

Editor Usage

[my_cta text="Get Started" url="/pricing" color="success"]

Understanding Attribute Parsing and Type Casting

When Blog_shortcode::do_shortcode() parses attributes via Blog_shortcode::parse_attributes(), keep two behaviors in mind:

  1. Quoted syntax: Attributes use key="value" or key='value' inside the opening bracket.
  2. Automatic type conversion: Values matching true, 1, yes, on are automatically cast to boolean true; values matching false, 0, no, off become boolean false; numeric strings become int.

Always account for both boolean and string values when inspecting flag attributes, or normalize them explicitly:

$is_open = ($atts['open'] === true || $atts['open'] === 'true' || $atts['open'] === '1');

Creating Enclosing and Nested Shortcodes

Enclosing shortcodes wrap inner text or markup between [tag] and [/tag]. Call polycms_do_shortcode($content) inside your callback so editors can nest shortcodes cleanly.

polycms_register_shortcode('my_highlight', function ($atts, $content = '') {
    $atts = shortcode_atts([
        'bg' => '#fef08a',
    ], $atts);

    // Allow only valid hex color codes
    $bg = preg_match('/^#[0-9a-fA-F]{3,6}$/', (string) $atts['bg']) ? (string) $atts['bg'] : '#fef08a';

    return '<span class="polycms-highlight px-1 rounded" style="background-color:' . esc_attr($bg) . ';">'
        . polycms_do_shortcode($content)
        . '</span>';
});

Usage in Content

[my_highlight bg="#dcfce7"]Important release update for RISE CRM administrators.[/my_highlight]

Practical Example 1: Accessible FAQ Accordion Shortcode

This enclosing shortcode renders a lightweight HTML5 accordion using &lt;details&gt; and &lt;summary&gt; with zero inline JavaScript required:

polycms_register_shortcode('my_accordion', function ($atts, $content = '') {
    $atts = shortcode_atts([
        'title' => 'Click to expand',
        'open'  => false,
    ], $atts);

    $open_attr = ($atts['open'] === true || $atts['open'] === 'true') ? ' open' : '';

    return '<details class="polycms-accordion border rounded p-3 mb-3"' . $open_attr . '>'
        . '<summary class="fw-semibold" style="cursor:pointer;">'
        . html_escape((string) $atts['title'])
        . '</summary>'
        . '<div class="accordion-body mt-2">'
        . polycms_do_shortcode($content)
        . '</div>'
        . '</details>';
});

Composing Nested Shortcodes

[my_accordion title="How do I enable the PolyCMS REST API?" open="true"]
  [my_highlight bg="#fef08a"]Tip:[/my_highlight] Open PolyCMS Settings, select the REST API tab, and generate a key.
[/my_accordion]

Practical Example 2: Dynamic Recent Posts Shortcode

Shortcodes can query live data from PolyCMS models using polycms_ci() and polycms_get_post_permalink():

polycms_register_shortcode('my_recent_posts', function ($atts) {
    $atts = shortcode_atts([
        'limit'       => 3,
        'category_id' => 0,
    ], $atts);

    $CI = &polycms_ci();
    $CI->load->model('polycms/Blog_post_model');

    $filters = [
        'status'     => 'published',
        'limit'      => max(1, min(12, (int) $atts['limit'])),
        'sort_by'    => 'published_at',
        'sort_order' => 'DESC',
    ];
    if ((int) $atts['category_id'] > 0) {
        $filters['category_id'] = (int) $atts['category_id'];
    }

    $posts = $CI->Blog_post_model->get($filters);
    if (empty($posts)) {
        return '';
    }

    $html = '<ul class="list-unstyled my-recent-posts">';
    foreach ($posts as $post) {
        $url = polycms_get_post_permalink($post);
        $html .= '<li class="mb-2"><a href="' . esc_attr($url) . '">'
            . html_escape($post->title)
            . '</a></li>';
    }
    $html .= '</ul>';

    return $html;
});

Overriding or Unregistering Shortcodes

To replace a built-in shortcode or disable one registered by another plugin, call polycms_unregister_shortcode() before registering your replacement:

polycms_add_action('polycms_init', function () {
    polycms_unregister_shortcode('polycms_tag');
    polycms_register_shortcode('polycms_tag', 'myplugin_custom_tag_handler');
});

Best Practices

  1. Always merge defaults with shortcode_atts(): Never assume editors provided every attribute.
  2. Escape all output strictly: Use html_escape(), esc_attr(), or polycms_safe_output(), and validate URLs and color codes before interpolating them into HTML attributes.
  3. Support nesting via polycms_do_shortcode($content): Pass inner content through polycms_do_shortcode() inside enclosing shortcodes.
  4. Namespace shortcode tags: Prefix custom tags with your plugin or brand identifier (for example, acme_pricing_table) to avoid collisions with core or third-party plugins.
  5. Register unconditionally at bootstrap: Register shortcodes when your plugin file loads rather than inside conditional frontend-only branches so REST API previews and MTBuilder rendering can resolve them consistently.

Need Developer Support?

If you need help writing or debugging custom shortcodes in PolyCMS for RISE CRM, leave a comment on our CodeCanyon portfolio page. Free developer support is included for all PolyCMS customers.

Related Documentation