Add Slide ID To Each Meta Slider Image

This PHP code uses the metaslider_slideshow_output filter hook to add a image id using the id for each slide, to each li class wrapping each slide image.

Here’s the default HTML output wrapping each slide image, inline styles and image tag removed for readability :

<li class="slide-583 ms-image " aria-roledescription="slide" aria-label="slide-583"></li>

And here’s the modified output adding the data-id.

<li class="slide-583 ms-image " aria-roledescription="slide" aria-label="slide-583" data-slide-id="583"></li>

All you need to do is paste the following PHP code to the end of your child themes functions file :

add_filter('metaslider_slideshow_output', 'add_data_slide_id_to_slides', 10, 3);
function add_data_slide_id_to_slides($slideshow, $slider_id, $settings) {
    // Use DOMDocument to manipulate the HTML output
    $dom = new DOMDocument();
    
    // Load the existing slideshow HTML
    libxml_use_internal_errors(true); // To suppress warnings for invalid HTML
    $dom->loadHTML($slideshow);
    libxml_clear_errors();
    
    // Get all the <li> elements within the slides container
    $lis = $dom->getElementsByTagName('li');
    
    foreach ($lis as $li) {
        // Check if the <li> has a class with "slide-" to extract the slide ID
        $classes = $li->getAttribute('class');
        
        if (preg_match('/slide-(\d+)/', $classes, $matches)) {
            // Extract the slide ID from the class
            $slide_id = $matches[1];
            
            // Add the data-slide-id attribute to the <li>
            $li->setAttribute('data-slide-id', $slide_id);
        }
    }

    // Save the modified HTML back to the slideshow output
    $slideshow = $dom->saveHTML();

    // Return the modified slideshow HTML
    return $slideshow;
}

You can also use the metaslider_flex_slider_image_attributes filter hook to add attributes to each slider image tag.

add_filter('metaslider_flex_slider_image_attributes', 'metaslider_add_rel_attribute_to_images', 10, 3);
function metaslider_add_rel_attribute_to_images($attributes, $slide, $slider_id) {
        $attributes['data-attr'] = 'test';
	return $attributes;
}

Uses the Metaslider_{type}_slider_image_attributes hook.

This code is used to add like buttons to meta slider images.

Was This Tutorial Helpful?

Free

$0

Access only to all free tutorials per month.



Monthly

$75

Access to 10 premium tutorials per month.


Tutorial Request


Includes code guarantee and coding support.

Yearly

$500

Access to 15 premium tutorials per month.


Monthly Tutorial Request


Includes code guarantee and priority coding support.