Question

I have seen many professional wordpress themes for sale that have shortcodes built in with which you could easily make posts like this:

[alert_box]This is an alert box which based on this short-code automatically
switches the CSS so it is easier than messing with classes every time[/alert_box]

How can I do this?

I know that it requires you to add something to the functions.php, though I haven't been able to figure out how.

Thank you, any help is appreciated.

Was it helpful?

Solution

See the Shortcode API article on the Codex for a tutorial and my Shortcode Plugin for some examples.

A very basic example for the functions.php:

/**
 * Shortcode for bloginfo()
 *
 * Usage: [bloginfo key="template_url"]
 *
 * @see http://codex.wordpress.org/Template_Tags/get_bloginfo
 * @source http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress
 * @param array $atts
 * @return string
 */
function bloginfo_shortcode($atts)
{
    extract( shortcode_atts( array( 'key' => 'name' ), $atts ) );
    return get_bloginfo( $key );
}
add_shortcode( 'bloginfo', 'bloginfo_shortcode' );

OTHER TIPS

For some stimulus to your example above...have the shortcode wrap the contents in a div or paragraph or blockquote or whatever wrapper you want, with some classes defined with it. That way they inherit the styling rules for those classes from the stylesheet. You could have .alert or .safe etc all defined already and then which type of notification you need determined the one used ;)

EDIT: Here's what I was thinking with my answer above, and perhaps someone else could use it themselves. For the example I'll use Alert, notice, and announcement

function announce_shortcode($atts, $content = null) { extract( shortcode_atts( array( 'type' => 'alert' ), $atts ) ); return ''.$content.'

'; } add_shortcode( 'announce', 'announce_shortcode' );

Then used like so [announce type="alert"]This is an alert![/announce] shown in red or however you wish to style. [announce type="notice"]This is just a notice[/announce] styled with milder colors than the alert, etc. Have the class names for alert and notice and whatnot defined in the css.

This was the need that I got out of reading the OP.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top