Skip to content

Instantly share code, notes, and snippets.

@xenioushk
Created April 29, 2025 05:58
Show Gist options
  • Save xenioushk/a5d5fedbfab5ec3bbb1ce0f9cb0a658c to your computer and use it in GitHub Desktop.
Save xenioushk/a5d5fedbfab5ec3bbb1ce0f9cb0a658c to your computer and use it in GitHub Desktop.
The Secret to Generating Dynamic WordPress Shortcodes (No One Talks About)
// Gather all the shortcode data.
$shortcode_data = [
'tag' => 'bwl_headline',
'title' => "Hello WordPress",
'sub_title' => "Generate dynamic wordpress shortcode.",
];
// Extract the shortcode data.
// For destructuring array data, you can also use the php list function instead of extract.
extract($shortcode_data);
// Exclude the tag.
$shortcode_attributes = array_diff_key(
$this->faq_data,
array_flip(
[
'tag',
]
)
);
// Build the shortcode attributes string.
$attributes_string = '';
foreach ( $shortcode_attributes as $key => $value ) {
$attributes_string .= sprintf( '%s="%s" ', esc_attr( $key ), esc_attr( $value ) );
}
// Generate the final shortcode string.
// Output: [bwl_headline title="Hello WordPress" sub_title="Generate dynamic wordpress shortcode."]
$shortcode_string = sprintf( '[%s %s/]', esc_attr( $shortcode ), trim( $attributes_string ) );
// Execute the shortcode.
echo do_shortcode($shortcode_string);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment