Here are three methods
Approach #1
It’s common to wrap the output with custom HTML. We can do that by using the post_gallery
filter and the gallery_shortcode()
callback:
/**
* HTML Wrapper - Support for a custom class attribute in the native gallery shortcode
*/
add_filter( 'post_gallery', function( $html, $attr, $instance )
{
if( isset( $attr['class'] ) && $class = $attr['class'] )
{
// Unset attribute to avoid infinite recursive loops
unset( $attr['class'] );
// Our custom HTML wrapper
$html = sprintf(
'<div class="wpse-gallery-wrapper-%s">%s</div>',
esc_attr( $class ),
gallery_shortcode( $attr )
);
}
return $html;
}, 10 ,3 );
Example:
If we set the class
attribute to the native gallery shortcode as small:
.
then the HTML output will be:
<div class="wpse-gallery-wrapper-small">
<!-- The default gallery HTML output comes here -->
</div>
where we can now target it with the .wpse-gallery-wrapper-small
class selector.
Approach #2
Another approach would be to modify the current class attribute with help of some string replacements. Let’s use the post_gallery
and the gallery_style
filters together:
/**
* HTML Replacement - Support for a custom class attribute in the native gallery shortcode
*/
add_filter( 'post_gallery', function( $html, $attr, $instance )
{
add_filter( 'gallery_style', function( $html ) use ( $attr )
{
if( isset( $attr['class'] ) && $class = $attr['class'] )
{
unset( $attr['class'] );
// Modify & replace the current class attribute
$html = str_replace(
"class="gallery ",
sprintf(
"class="gallery wpse-gallery-%s ",
esc_attr( $class )
),
$html
);
}
return $html;
} );
return $html;
}, 10 ,3 );
Example:
Using this shortcode:
.
will give the following HTML output:
<style>...</style>
<div id="gallery-1" class="gallery wpse-gallery-small ... "> ... </div>
where the class selector is .wpse-gallery-wrapper-small
.
Approach #3
Use the default id selector for the gallery instance.
id='gallery-1'
or the default class selectors:
class="gallery galleryid-123 gallery-columns-3 gallery-size-thumbnail"
where 123
is the current post id.