0
0
Wordpressframework~30 mins

Enclosing shortcodes in Wordpress - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating and Using Enclosing Shortcodes in WordPress
📖 Scenario: You are building a WordPress site and want to create a custom shortcode that wraps content inside a styled box. This box will highlight the enclosed text with a border and background color.
🎯 Goal: Build a WordPress enclosing shortcode called highlight_box that wraps any content placed between its opening and closing tags inside a styled <div>. The box should have a border and background color to make the content stand out.
📋 What You'll Learn
Create a function called highlight_box_shortcode that accepts $atts and $content parameters
Add a shortcode tag called highlight_box linked to the function
Use shortcode_atts to set a default background color attribute bg_color with value #ffffcc
Return the $content wrapped inside a <div> with inline styles for border and background color
Ensure the shortcode is enclosing, so it processes content between [highlight_box] and [/highlight_box]
💡 Why This Matters
🌍 Real World
Enclosing shortcodes are useful for wrapping content blocks with special styles or behaviors in WordPress posts and pages without editing theme files.
💼 Career
Knowing how to create and register enclosing shortcodes is a common task for WordPress developers customizing sites and plugins.
Progress0 / 4 steps
1
Create the shortcode function
Create a function called highlight_box_shortcode that accepts two parameters: $atts and $content. Inside the function, return the $content wrapped inside a <div> with a border style 1px solid #ccc and background color #ffffcc. Use do_shortcode on $content to allow nested shortcodes.
Wordpress
Need a hint?

Remember to use do_shortcode on the $content so that any shortcodes inside the content also work.

2
Register the shortcode tag
Add a line to register the shortcode tag highlight_box using add_shortcode and link it to the function highlight_box_shortcode.
Wordpress
Need a hint?

Use add_shortcode with the tag name and the function name as parameters.

3
Add background color attribute support
Inside the highlight_box_shortcode function, use shortcode_atts to set a default attribute bg_color with value #ffffcc. Replace the hardcoded background color in the <div> style with the value from $atts['bg_color'].
Wordpress
Need a hint?

Use shortcode_atts to merge default attributes with user-provided ones.

4
Complete the enclosing shortcode setup
Ensure the function parameter $content has a default value null and that the function returns the content wrapped in the styled <div>. Confirm the shortcode tag highlight_box is registered with add_shortcode. This completes the enclosing shortcode setup.
Wordpress
Need a hint?

Check that the function and shortcode registration are complete and correct.