admin管理员组

文章数量:1122832

I'm using WordPress 6.5 with the old editor, I'm trying to add a CSS class on the div gallery when it specified in the shortcode, the code doesn't work, can you help me ?

function custom_gallery_class($output, $attr) {
    if (isset($attr['class'])) {
        $output = str_replace('<div class="gallery', '<div class="gallery ' . esc_attr($attr['class']), $output);
    }
    return $output;
}
add_filter('post_gallery', 'custom_gallery_class', 10, 2);

Custom shortcode example :

[gallery size="medium" columns="2" link="file" class="custom-class" ids="46729,46728"]

Expected result :

<div id="gallery-1" class="gallery custom-class galleryid-48105 gallery-columns-2 gallery-size-medium">...</div>

Result :

<div id="gallery-1" class="gallery galleryid-48105 gallery-columns-2 gallery-size-medium">...</div>

I'm using WordPress 6.5 with the old editor, I'm trying to add a CSS class on the div gallery when it specified in the shortcode, the code doesn't work, can you help me ?

function custom_gallery_class($output, $attr) {
    if (isset($attr['class'])) {
        $output = str_replace('<div class="gallery', '<div class="gallery ' . esc_attr($attr['class']), $output);
    }
    return $output;
}
add_filter('post_gallery', 'custom_gallery_class', 10, 2);

Custom shortcode example :

[gallery size="medium" columns="2" link="file" class="custom-class" ids="46729,46728"]

Expected result :

<div id="gallery-1" class="gallery custom-class galleryid-48105 gallery-columns-2 gallery-size-medium">...</div>

Result :

<div id="gallery-1" class="gallery galleryid-48105 gallery-columns-2 gallery-size-medium">...</div>
Share Improve this question edited Apr 29, 2024 at 9:54 cjbj 15k16 gold badges42 silver badges89 bronze badges asked Apr 29, 2024 at 0:46 BarristaBarrista 12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

If you look at the gallery shortcode you will see that you are using the wrong filter. With post_gallery you can override the complete html of the shortcode. Your code performs a str_replace on an empty string, resulting in an empty return and subsequently the generation of the default gallery html.

Further on there is a filter called gallery_style which is meant to filter the gallery styles, but since the opening div is included you can also use to modify the classes.

本文标签: phpAdding a css class to the gallery