Shortcodes

The Shortcode API

Introduced in WordPress 2.5 is the Shortcode API, a simple set of functions for creating macro codes for use in post content. For instance, the following shortcode (in the post/page content) would add a photo gallery into the page:
[gallery]
It enables plugin developers to create special kinds of content (e.g. forms, content generators) that users can attach to certain pages by adding the corresponding shortcode into the page text.
The Shortcode API makes it easy to create shortcodes that support attributes like this:
[gallery id="123" size="medium"]
The API handles all the tricky parsing, eliminating the need for writing a custom regular expression for each shortcode. Helper functions are included for setting and fetching default attributes. The API supports both self-closing and enclosing shortcodes.
As a quick start for those in a hurry, here's a minimal example of the PHP code required to create a shortcode:
//[foobar]
function foobar_func( $atts ){
 return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );
This will create [foobar] shortcode that returns as: foo and bar
With attributes:
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
    $a = shortcode_atts( array(
        'foo' => 'something',
        'bar' => 'something else',
    ), $atts );

    return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );
This creates a "[bartag]" shortcode that supports two attributes: ["foo" and "bar"]. Both attributes are optional and will take on default options [foo="something" bar="something else"] if they are not provided. The shortcode will return as foo = {the value of the foo attribute}.

Overview

Shortcodes are written by providing a handler function. Shortcode handlers are broadly similar to WordPress filters: they accept parameters (attributes) and return a result (the shortcode output).
Shortcode names should be all lowercase and use all letters, but numbers and underscores should work fine too. Be wary of using hyphens (dashes), you'll be better off not using them.
The add_shortcode function is used to register a shortcode handler. It takes two parameters: the shortcode name (the string used in a post body), and the callback function name.
Three parameters are passed to the shortcode callback function. You can choose to use any number of them including none of them.
  • $atts - an associative array of attributes, or an empty string if no attributes are given
  • $content - the enclosed content (if the shortcode is used in its enclosing form)
  • $tag - the shortcode tag, useful for shared callback functions
The API call to register the shortcode handler would look something like this:
add_shortcode( 'myshortcode', 'my_shortcode_handler' );
When the_content is displayed, the shortcode API will parse any registered shortcodes such as "[myshortcode]", separate and parse the attributes and content, if any, and pass them the corresponding shortcode handler function. Any string returned (not echoed) by the shortcode handler will be inserted into the post body in place of the shortcode itself.
Shortcode attributes are entered like this:
[myshortcode foo="bar" bar="bing"]
These attributes will be converted into an associative array like the following, passed to the handler function as its $atts parameter:
array( 'foo' => 'bar', 'bar' => 'bing' )
The array keys are the attribute names; array values are the corresponding attribute values. In addition, the zeroeth entry ($atts[0]) will hold the string that matched the shortcode regex, but ONLY IF that is different from the callback name. See the discussion of attributes, below.

Handling Attributes

The raw $atts array may include any arbitrary attributes that are specified by the user. (In addition, the zeroeth entry of the array may contain the string that was recognized by the regex; see the note below.)
In order to help set default values for missing attributes, and eliminate any attributes that are not recognized by your shortcode, the API provides a shortcode_atts() function.
shortcode_atts() resembles the wp_parse_args function, but has some important differences. Its parameters are:
shortcode_atts( $defaults_array, $atts );
Both parameters are required. $defaults_array is an associative array that specifies the recognized attribute names and their default values. $atts is the raw attributes array as passed into your shortcode handler. shortcode_atts() will return a normalized array containing all of the keys from the $defaults_array, filled in with values from the $atts array if present. For example:
$a = shortcode_atts( array(
    'title' => 'My Title',
    'foo' => 123,
), $atts );
If $atts were to contain array( 'foo' => 456, 'bar' => 'something' ), the resulting $a would be array( 'title' => 'My Title', 'foo' => 456 ). The value of $atts['foo'] overrides the default of 123. $atts['title'] is not set, so the default 'My Title' is used. There is no 'bar' item in the defaults array, so it is not included in the result.
Attribute names are always converted to lowercase before they are passed into the handler function. Values are untouched. [myshortcode FOO="BAR"] produces $atts = array( 'foo' => 'BAR' ).
A suggested code idiom for declaring defaults and parsing attributes in a shortcode handler is as follows:
function my_shortcode_handler( $atts, $content = null ) {
    $a = shortcode_atts( array(
        'attr_1' => 'attribute 1 default',
        'attr_2' => 'attribute 2 default',
        // ...etc
    ), $atts );
}
This will parse the attributes, set default values, eliminate any unsupported attributes, and store the results in a local array variable named $a with the attributes as keys - $a['attr_1'], $a['attr_2'], and so on. In other words, the array of defaults approximates a list of local variable declarations.

IMPORTANT TIP - Don't use camelCase or UPPER-CASE for your $atts attribute names
$atts values are lower-cased during shortcode_atts( array( 'attr_1' => 'attr_1 default', // ...etc ), $atts ) processing, so you might want to just use lower-case.


NOTE on confusing regex/callback name reference
The zeroeth entry of the attributes array ($atts[0]) will contain the string that matched the shortcode regex, but ONLY if that differs from the callback name, which otherwise appears as the third argument to the callback function.
(Appears to always appear as third argument as of 2.9.2.)
 add_shortcode('foo','foo'); // two shortcodes referencing the same callback
 add_shortcode('bar','foo');
    produces this behavior:
 [foo a='b'] ==> callback to: foo(array('a'=>'b'),NULL,"foo");
 [bar a='c'] ==> callback to: foo(array(0 => 'bar', 'a'=>'c'),NULL,"");
This is confusing and perhaps reflects an underlying bug, but an overloaded callback routine can correctly determine what shortcode was used to call it, by checking BOTH the third argument to the callback and the zeroeth attribute. (It is NOT an error to have two shortcodes reference the same callback routine, which allows for common code.)

Output

The return value of a shortcode handler function is inserted into the post content output in place of the shortcode macro. Remember to use return and not echo - anything that is echoed will be output to the browser, but it won't appear in the correct place on the page.
Shortcodes are parsed after wpautop and wptexturize post formatting has been applied (but see the note below about 2.5.0 and 2.5.1 differences). This means that your shortcode output HTML won't automatically have curly quotes applied, p and br tags added, and so on. If you do want your shortcode output to be formatted, you should call wpautop() or wptexturize() directly when you return the output from your shortcode handler.
wpautop recognizes shortcode syntax and will attempt not to wrap p or br tags around shortcodes that stand alone on a line by themselves. Shortcodes intended for use in this manner should ensure that the output is wrapped in an appropriate block tag such as <p> or <div>.
Note: in WordPress 2.5.0, shortcodes were parsed before post formatting was applied, so the shortcode output HTML was sometimes wrapped in p or br tags. This was incorrect behaviour that has been fixed in 2.5.1.
If the shortcode produces a lot of HTML then ob_start can be used to capture output and convert it to a string as follows:-
function my_shortcode() {
 ob_start();
 ?> <HTML> <here> ... <?php
 return ob_get_clean();
}

Enclosing vs self-closing shortcodes

The examples above show self-closing shortcode macros such as [myshortcode]. The API also supports enclosing shortcodes such as [myshortcode]content[/myshortcode].
If a shortcode macro is used to enclose content, its handler function will receive a second parameter containing that content. Users might write shortcodes in either form, so it is necessary to allow for either case by providing a default value for the second parameter to your handler function:
function my_shortcode_handler( $atts, $content = null )
is_null( $content ) can be used to distinguish between the self-closing and enclosing cases.
When content is enclosed, the complete shortcode macro including its content will be replaced with the function output. It is the responsibility of the handler function to provide any necessary escaping or encoding of the raw content string, and include it in the output.
Here's a trivial example of an enclosing shortcode:
function caption_shortcode( $atts, $content = null ) {
 return '<span class="caption">' . $content . '</span>';
}
add_shortcode( 'caption', 'caption_shortcode' );
When used like this:
[caption]My Caption[/caption]
The output would be:
<span class="caption">My Caption</span>
Since $content is included in the return value without any escaping or encoding, the user can include raw HTML:
[caption]<a href="http://example.com/">My Caption</a>[/caption]
Which would produce:
<span class="caption"><a href="http://example.com/">My Caption</a></span>
This may or may not be intended behaviour - if the shortcode should not permit raw HTML in its output, it should use an escaping or filtering function to deal with it before returning the result.
The shortcode parser uses a single pass on the post content. This means that if the $content parameter of a shortcode handler contains another shortcode, it won't be parsed:
[caption]Caption: [myshortcode][/caption]
This would produce:
<span class="caption">Caption: [myshortcode]</span>
If the enclosing shortcode is intended to permit other shortcodes in its output, the handler function can call do_shortcode() recursively:
function caption_shortcode( $atts, $content = null ) {
   return '<span class="caption">' . do_shortcode($content) . '</span>';
}
In the previous example, this would ensure the "[myshortcode]" macro in the enclosed content is parsed, and its output enclosed by the caption span:
<span class="caption">Caption: The result of myshortcode's handler function</span>
The parser does not handle mixing of enclosing and non-enclosing forms of the same shortcode as you would want it to. For example, if you have:
[myshortcode example='non-enclosing' /] non-enclosed content [myshortcode] enclosed content [/myshortcode]
Instead of being treated as two shortcodes separated by the text " non-enclosed content ", the parser treats this as a single shortcode enclosing " non-enclosed content [myshortcode] enclosed content".
Enclosing shortcodes support attributes in the same way as self-closing shortcodes. Here's an example of the caption_shortcode() improved to support a 'class' attribute:
function caption_shortcode( $atts, $content = null ) {
 $a = shortcode_atts( array(
  'class' => 'caption',
 ), $atts );

 return '<span class="' . esc_attr($a['class']) . '">' . $content . '</span>';
}
[caption class="headline"]My Caption[/caption]
<span class="headline">My Caption</span>

Other features in brief

  • The parser supports xhtml-style closing shortcodes like "[myshortcode /]", but this is optional.
  • Shortcode macros may use single or double quotes for attribute values, or omit them entirely if the attribute value does not contain spaces. [myshortcode foo='123' bar=456] is equivalent to [myshortcode foo="123" bar="456"]. Note the attribute value in the last position may not end with a forward slash because the feature in the paragraph above will consume that slash.
  • For backwards compatibility with older ad-hoc shortcodes, attribute names may be omitted. If an attribute has no name it will be given a positional numeric key in the $atts array. For example, [myshortcode 123] will produce $atts = array( 0 => 123 ). Positional attributes may be mixed with named ones, and quotes may be used if the values contain spaces or other significant characters.

Function reference

The following Shortcode API functions are available:
function add_shortcode( $tag, $func )
Registers a new shortcode handler function. $tag is the shortcode string as written by the user (without braces), such as "myshortcode". $func is the handler function name.
Only one handler function may exist for a given shortcode. Calling add_shortcode() again with the same $tag name will overwrite the previous handler.
function remove_shortcode( $tag )
Deregisters an existing shortcode. $tag is the shortcode name as used in add_shortcode().
function remove_all_shortcodes()
Deregisters all shortcodes.
function shortcode_atts( $pairs, $atts )
Process a raw array of attributes $atts against the set of defaults specified in $pairs. Returns an array. The result will contain every key from $pairs, merged with values from $atts. Any keys in $atts that do not exist in $pairs are ignored.
function do_shortcode( $content )
Parse any known shortcode macros in the $content string. Returns a string containing the original content with shortcode macros replaced by their handler functions' output.
do_shortcode() is registered as a default filter on 'the_content' with a priority of 11.

Limitations

Nested Shortcodes

The shortcode parser correctly deals with nested shortcode macros, provided their handler functions support it by recursively calling do_shortcode():
[tag-a]
   [tag-b]
      [tag-c]
   [/tag-b]
[/tag-a]
However the parser will fail if a shortcode macro is used to enclose another macro of the same name:
[tag-a]
   [tag-a]
   [/tag-a]
[/tag-a]
This is a limitation of the context-free regexp parser used by do_shortcode() - it is very fast but does not count levels of nesting, so it can't match each opening tag with its correct closing tag in these cases.
In future versions of WordPress, it may be necessary for plugins having a nested shortcode syntax to ensure that the wptexturize() processor does not interfere with the inner codes. It is recommended that for such complex syntax, the no_texturize_shortcodes filter should be used on the outer tags. In the examples used here, tag-a should be added to the list of shortcodes to not texturize. If the contents of tag-a or tag-b still need to be texturized, then you can call wptexturize() before calling do_shortcode() as described above.

Unregistered Names

Some plugin authors have chosen a strategy of not registering shortcode names, for example to disable a nested shortcode until the parent shortcode's handler function is called. This may have unintended consequences, such as failure to parse shortcode attribute values. For example:
[tag-a unit="north"]
   [tag-b size="24"]
      [tag-c color="red"]
   [/tag-b]
[/tag-a]
Starting with version 4.0.1, if a plugin fails to register tag-b and tag-c as valid shortcodes, the wptexturize() processor will output the following text prior to any shortcode being parsed:
[tag-a unit="north"]
   [tag-b size=&#8221;24&#8221;]
      [tag-c color=&#8221;red&#8221;]
   [/tag-b]
[/tag-a]
Unregistered shortcodes should be considered normal plain text that have no special meaning, and the practice of using unregistered shortcodes is discouraged. If you must enclose raw code between shortcode tags, at least consider using the no_texturize_shortcodes filter to prevent texturization of the contents of tag-a:
add_shortcode( 'tag-a', 'my_tag_a_handler' );
add_filter( 'no_texturize_shortcodes', 'ignore_tag_a' );

function ignore_tag_a( $list ) {
  $list[] = 'tag-a';
  return $list;
}

Unclosed Shortcodes

In certain cases the shortcode parser cannot correctly deal with the use of both closed and unclosed shortcodes. For instance in this case the parser will only correctly identify the second instance of the shortcode:
[tag]
[tag]
   CONTENT
[/tag]
However in this case the parser will identify both:
[tag]
   CONTENT
[/tag]
[tag]

Hyphens

Note: The behavior described below involving shortcodes with hyphens ('-') still applies in WordPress 3+. This could be due to a bug in do_shortcode() or get_shortcode_regex().
Take caution when using hyphens in the name of your shortcodes. In the following instance WordPress may see the second opening shortcode as equivalent to the first (basically WordPress sees the first part before the hyphen):
[tag]
[tag-a]
It all depends on which shortcode is defined first. If you are going to use hyphens then define the shortest shortcode first.
To avoid this, use an underscore or simply no separator:
[tag]
[tag_a]

[tag]
[taga]
If the first part of the shortcode is different from one another, you can get away with using hyphens:
[tag]
[tagfoo-a]
Important: Using hyphens can have implications that you may not be aware of; such as if other installed shortcodes also are use hyphens, the use of generic words with hyphens may cause collisions (if shortcodes are used together within the same request):
// plugin-A
[is-logged-in]

// plugin-B
[is-admin]

Square Brackets

The shortcode parser does not accept square brackets within attributes. Thus the following will fail:
[tag attribute="[Some value]"]
Tags surrounded by cosmetic brackets are not yet fully supported by wptexturize() or its filters. These codes may give unexpected results:
[I put random text near my captions. [caption]]
Note: these limitations may change in future versions of WordPress, you should test to be absolutely sure.

HTML

Starting with version 3.9.3, use of HTML is limited inside shortcode attributes. For example, this shortcode will not work correctly because it contains a '>' character:
[tag value1="35" value2="25" compare=">"]
Version 4.0 is designed to allow validated HTML, so this will work:
[tag description="<b>Greetings</b>"]
The suggested workaround for HTML limitations is to use HTML encoding for all user input, and then add HTML decoding in the custom shortcode handler. Extra API functions are planned.
Full usage of HTML in shortcode attributes was never officially supported, but will be considered as a possible enhancement in future versions.

Formal Syntax

WordPress shortcodes do not use special characters in the same way as HTML. The square braces may seem magical at first glance, but they are not truly part of any language. For example:
[gallery]
The gallery shortcode is parsed by the API as a special symbol because it is a registered shortcode. On the other hand, square braces are simply ignored when a shortcode is not registered:
[randomthing]
The randomthing symbol and its square braces are ignored because they are not part of any registered shortcode.
In a perfect world, any [*] symbol could be handled by the API, but we have to consider the following challenges: Square braces are allowed in HTML and are not always shortcodes, angle braces are allowed inside of shortcodes only in limited situations, and all of this code must run through multiple layers of customizeable filters and parsers before output. Because of these language compatibility issues, square braces can't be magical.
The shortcode syntax uses these general parts:
[name attributes close]
[name attributes]Any HTML or shortcode may go here.[/name]
Escaped shortcodes are identical but have exactly two extra braces:
[[name attributes close]]
[[name attributes]Any HTML or shortcode may go here.[/name]]
Again, the shortcode name must be registered, otherwise all four examples would be ignored.

Names

Shortcode names must never contain the following characters:
  • Square braces: [ ]
  • Forward slash: /
  • Whitespace: space linefeed tab
  • Non-printing characters: \x00 - \x20
It is recommended to also avoid HTML-special characters in the names of shortcodes:
  • Angle braces: < >
  • Ampersand: &
  • Quotes: ' "

Attributes

Attributes are optional. A space is required between the shortcode name and the shortcode attributes. When more than one attribute is used, each attribute must be separated by at least one space.
Each attribute should conform to one of these formats:
attribute_name = 'value'
attribute_name = "value"
attribute_name = value
"value"
value
Attribute names are optional and should contain only the following characters for compatibility across all platforms:
  • Upper-case and lower-case letters: A-Z a-z
  • Digits: 0-9
  • Underscore: _
Spaces are not allowed in attribute names. Optional spaces may be used between the name and the = sign. Optional spaces may also be used between the = sign and the value.
Attribute values must never contain the following characters:
  • Square braces: [ ]
  • Quotes: " '
Unquoted values also must never contain spaces.
HTML characters < and > have only limited support in attributes.
The recommended method of escaping special characters in shortcode attributes is HTML encoding. Most importantly, any user input appearing in a shortcode attribute must be escaped or stripped of special characters.
Note that double quotes are allowed inside of single-quoted values and vice versa, however this is not recommended when dealing with user input.
The following characters, if they are not escaped within an attribute value, will be automatically stripped and converted to spaces:
  • No-break space: \xC2\xA0
  • Zero-width space: \xE2\x80\x8B

Self-Closing

The self-closing marker, a single forward slash, is optional. Space before the marker is optional. Spaces are not allowed after the marker.
[example /]
The self-closing marker is purely cosmetic and has no effect except that it will force the shortcode parser to ignore any closing tag that follows it.
The enclosing type shortcodes may not use a self-closing marker.

Escaping

WordPress attempts to insert curly quotes between the [name] and [/name] tags. It will process that content just like any other. As of 4.0.1, unregistered shortcodes are also "texturized" and this may give unexpected curly quotes:
[randomthing param="test"]
A better example would be:
<code>[randomthing param="test"]</code>
The <code> element is always avoided for the sake of curly quotes.
Registered shortcodes are still processed inside of <code> elements. To escape a registered shortcode for display on your website, the syntax becomes:
[[caption param="test"]]
... which will output ...
[caption param="test"]
 
 
 

Audio Shortcode

The Audio feature allows you to embed audio files and play them back using a simple Shortcode. This was added as of WordPress 3.6 and is used like this:
[audio]
You can also use build in embeds and simply put the media file on it's own line:
My cool content http://my.mp3s.com/cool/songs/coolest.mp3 More cool content

Practical Usage

I have an old post that has an audio file in the Media Library attached to it, and I want to use the new shortcode:
[audio]
I have the URL for an MP3, from the Media Library or external, that I want to play:
[audio src="audio-source.mp3"]
I have a source URL and fallbacks for other HTML5-supported filetypes:
[audio mp3="source.mp3" ogg="source.ogg" wav="source.wav"]

Options

The following basic options are supported:
src
(string) (optional) The source of your audio file. If not included it will auto-populate with the first audio file attached to the post. You can use the following options to define specific filetypes, allowing for graceful fallbacks:
  • 'mp3', 'm4a', 'ogg', 'wav', 'wma'
Default: First audio file attached to the post
loop
(string) (optional) Allows for the looping of media. Defaults to "off".
  • "off" - ("default") does not loop the media
  • "on" - media will loop to beginning when finished and automatically continue playing
Default: "off"
autoplay
(string) (optional) Causes the media to automatically play as soon as the media file is ready. Defaults to "off".
  • "off" - ("default") does not automatically play the media
  • "on" - Media will play as soon as the media is ready
Default: "off"
preload
(string) (optional) Specifies if and how the audio should be loaded when the page loads. Defaults to "none".
  • "none" - ("default") the audio should not be loaded when the page loads
  • "auto" - the audio should be loaded entirely when the page loads
  • "metadata" - only metadata should be loaded when the page loads
Default: "none"
  

Caption Shortcode

The Caption feature allows you to wrap captions around content using a simple Shortcode. This is primarily used with individual images
[caption]<image> Caption[/caption] Practical usage is like this:
[caption id="attachment_6" align="alignright" width="300"]<img src="http://localhost/wp-content/uploads/2010/07/800px-Great_Wave_off_Kanagawa2-300x205.jpg" alt="Kanagawa" title="The Great Wave" width="300" height="205" class="size-medium wp-image-6" /> The Great Wave[/caption] Which looks like this:
image-caption-theme.png

Options

The following basic options are supported:
id
A unique HTML ID that you can change to use within your CSS.
class
Custom class that you can use within your CSS.
align
The alignment of the caption within the post. Valid values are: alignnone (default), aligncenter, alignright, and alignleft.
width
How wide the caption should be in pixels. This attribute is required and must have a value greater than or equal to 1.

Source File

The caption shortcode is located in wp-includes/media.php.

Resources



In A Nutshell

To embed a video or another object into a post or page, place its URL into the content area. Make sure the URL is on its own line and not hyperlinked (clickable when viewing the post).
For example:
Check out this cool video:

http://www.youtube.com/watch?v=dQw4w9WgXcQ

That was a cool video.
WordPress will automatically turn the URL into a YouTube embed and provide a live preview in the visual editor.
Another option is to wrap the URL in the [embed] shortcode. It will accomplish the same effect, but does not require the URL to be on its own line. Using [embed] allows for the inclusion of a maximum (but not fixed) width and height: [embed width="123" height="456"]...[/embed]
If WordPress fails to embed the URL, the post will contain a hyperlink to the URL.
Also note that you cannot use do_shortcode as usual with [embed], however there is a workaround on the do_shortcode page.

oEmbed

The easy embedding feature is mostly powered by oEmbed, a protocol for site A (such as your blog) to ask site B (such as YouTube) for the HTML needed to embed content from site B.
oEmbed was designed to avoid the need to copy and paste HTML from the site hosting the media you wish to embed. It supports videos, images, text, and more.

Does This Work With Any URL?

No, not by default. WordPress will only embed URLs matching an internal whitelist. This is for security purposes
 
  

Gallery Shortcode

The Gallery feature allows you to add one or more image galleries to your posts and pages using a simple Shortcode. Since WordPress 2.5 and up until 3.5, the gallery shortcode was commonly used in its most basic form:
[gallery] Following 3.5, gallery shortcodes now include the image IDs by default. Like this:
[gallery ids="729,732,731,720"] It's important to note that this style of gallery shortcode is not new to 3.5, previously we could use the include attribute. However it is much easier to generate and manage with the new Media Workflow introduced in 3.5.
Specifying IDs in your shortcode allows you to include images in your gallery that aren't necessarily "attached" to your post — that is to say, not uploaded from within your post or page. This flexibility allows you to create and embed any number of galleries containing any number of images!
Note: If you choose to just use the "barebones" version of the [gallery] shortcode in your post or page, only images that are "attached" to that post or page will be displayed.

Output Options

There are several options that may be specified using this syntax:
[gallery option1="value1" option2="value2"] You can also print a gallery directly in a template like so:
<?php echo do_shortcode('[gallery option1="value1"]'); ?> This works too:
<?php $gallery_shortcode = '[gallery id="' . intval( $post->post_parent ) . '"]'; print apply_filters( 'the_content', $gallery_shortcode );  ?>

Options

The following basic options are supported:
orderby 
specify how to sort the display thumbnails. The default is "menu_order". Options:
  • menu_order - you can reorder the images in the Gallery tab of the Add Media pop-up
  • title - order by the title of the image in the Media Library
  • post_date - sort by date/time
  • rand - order randomly
  • ID
order 
specify the sort order used to display thumbnails. ASC or DESC. For example, to sort by ID, DESC:
[gallery order="DESC" orderby="ID"]
columns 
specify the number of columns. The gallery will include a break tag at the end of each row, and calculate the column width as appropriate. The default value is 3. If columns is set to 0, no row breaks will be included. For example, to display a 4 column gallery:
[gallery columns="4"]
id 
specify the post ID. The gallery will display images which are attached to that post. The default behavior, if no ID is specified, is to display images attached to the current post. For example, to display images attached to post 123:
[gallery id="123"]
size 
specify the image size to use for the thumbnail display. Valid values include "thumbnail", "medium", "large", "full" and any other additional image size that was registered with add_image_size(). The default value is "thumbnail". The size of the images for "thumbnail", "medium" and "large" can be configured in WordPress admin panel under Settings > Media. For example, to display a gallery of medium sized images:
[gallery size="medium"] Some advanced options are available:
itemtag 
the name of the XHTML tag used to enclose each item in the gallery. The default is "dl".
icontag 
the name of the XHTML tag used to enclose each thumbnail icon in the gallery. The default is "dt".
captiontag
the name of the XHTML tag used to enclose each caption. The default is "dd". For example, to change the gallery markup to use div, span and p tags:
[gallery itemtag="div" icontag="span" captiontag="p"]
link
Specify where you want the image to link. The default value links to the attachment's permalink. Options:
  • file - Link directly to image file
  • none - No link
[gallery link="file"]
include
comma separated attachment IDs to show only the images from these attachments.
[gallery include="23,39,45"]
exclude
comma separated attachment IDs excludes the images from these attachments. Please note that include and exclude cannot be used together.
[gallery exclude="21,32,43"]

Developers - Things to consider

The default expected behavior for a gallery that has no explicit IDs stated is to add all images that have the post as post parent assigned. In other words, add all images that were uploaded using the "Add media" button/link on this post edit screen. Keep in mind that this as well means that every attachment added to that post later on will be interpreted to be part of the gallery. No matter if it was displayed as plain attachment or not.
This should be the default fallback if no argument were provided: ...lorem [gallery] ipsum...
$attachments = get_children( array( 'post_parent' => $attr['id'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $attr['order'], 'orderby' => $attr['orderby'], ) ); And stop using extract() on shortcode_atts() (or anywhere else). IDEs are not able to backtrace that.

Source File

The gallery shortcode is located in wp-includes/media.php.
  

Video Shortcode

The Video feature allows you to embed video files and play them back using a simple Shortcode. This was added as of WordPress 3.6 and is used like this:
[video]
You can also use build in embeds and simply put the media file on it's own line:
My cool content http://my.movies.com/cool/movie/coolest.mov More cool content

Practical Usage

I have an old post that has a video file in the Media Library attached to it, and I want to use the new shortcode:
[video]
I have the URL for an mp4, from the Media Library or external, that I want to play:
[video src="video-source.mp4"]
I have a source URL and fallbacks for other HTML5-supported filetypes:
[video mp4="source.mp4" ogv="source.ogv" mov="source.mov"]

Options

The following basic options are supported:
src
(string) (optional) The source of your video file. If not included it will auto-populate with the first video file attached to the post. You can use the following options to define specific filetypes, allowing for graceful fallbacks:
  • 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'
Default: First video file attached to the post
poster
(string) (optional) Defines image to show as placeholder before the media plays.
Default: None
loop
(string) (optional) Allows for the looping of media. Defaults to "off".
  • "off" - ("default") does not loop the media
  • "on" - media will loop to beginning when finished and automatically continue playing
Default: "off"
autoplay
(string) (optional) Causes the media to automatically play as soon as the media file is ready. Defaults to "off".
  • "off" - ("default") does not automatically play the media
  • "on" - Media will play as soon as the media is ready
Default: "off"
preload
(string) (optional) Specifies if and how the video should be loaded when the page loads. Defaults to "metadata".
  • "metadata" - ("default") only metadata should be loaded when the page loads
  • "none" - the video should not be loaded when the page loads
  • "auto" - the video should be loadaded entirely when the page loads
Default: "metadata"
height
(integer) (required) Defines height of the media. Value is automatically detected on file upload.
Default: [Media file height]
width
(integer) (required) Defines width of the media. Value is automatically detected on file upload.
Default: [Media file width]

Source File

The video shortcode is located in wp-includes/media.php.



 

Playlist Shortcode

This article is marked as in need of editing. You can help Codex by editing it.
The playlist shortcode implements the functionality of displaying a collection of WordPress audio or video files in a post using a simple Shortcode. This was added as of WordPress 3.9 and is used like this:
[playlist]

Attributes

The playlist shortcode has several attributes, which are making it possible to alter its output.
The default values for the attributes are:

Defaults


<?php array(
    
'type'          => 'audio',
    
'order'         => 'ASC',
    
'orderby'       => 'menu_order ID',
    
'id'            => $post $post->ID 0,
    
'include'       => ,
    
'exclude'       => 
,
    
'style'         => 'light',
    
'tracklist'     => true,
    
'tracknumbers'  => true,
    
'images'        => true,
    
'artists'       => true);

Possible values

Some values do set others depending on their arguments. Keep that in mind when something does not work.
'type'
(string) (Optional) Type of playlist to display. Accepts 'audio' or 'video'.
Default: 'audio'
'order'
(string) (Optional) Designates ascending or descending order of items in the playlist. Accepts 'ASC', 'DESC'.
Default: 'ASC'
  • NOTE: RAND won't work here, the documentation that was once here is incorrect, see Trac Ticket #29629
'orderby'
(string) (Optional) Any column, or columns, to sort the playlist. If $ids are passed, this defaults to the order of the $ids array ('post__in').
Default: 'menu_order ID'
  • NOTE: rand (random playlist order) will work when set here
'id'
(int) (Optional) If an explicit $ids array is not present, this parameter will determine which attachments are used for the playlist.
Default: the current post ID
'ids'
(array) (Optional) Create a playlist out of these explicit attachment IDs. If empty, a playlist will be created from all $type attachments of $id.
Default: empty
'exclude'
(array) (Optional) List of specific attachment IDs to exclude from the playlist.
Default: empty
'style'
(string) (Optional) Playlist style to use. Accepts 'light' or 'dark'.
Default: 'light'
'tracklist'
(bool) (Optional) Whether to show or hide the playlist.
Default: true
'tracknumbers'
(bool) (Optional) Whether to show or hide the numbers next to entries in the playlist.
Default: true
'images'
(bool) (Optional) Show or hide the video or audio thumbnail (Featured Image/post thumbnail).
Default: true
'artists'
(bool) (Optional) Whether to show or hide artist name in the playlist.
Default: true

Usage

Generally shortcodes are used by adding them to the content of the post editor.
Basic, with default values:
[playlist] Changing style to dark:
[playlist style="dark"] Changing type to video:
[playlist type="video"] Specifying ids of audio, it's the default, files out of the media library:
[playlist ids="123,456,789"] Specifying ids of video files out of the media library and changing style:
[playlist type="video" ids="123,456,789" style="dark"]

 
 
 
 
 
 
 
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment