Search

How to Stop and Play Animated GIF on Click in WordPress (without Plugin)

Having control of stopping and playing for GIF animations can enhance your user experiences when they visit your website. Moreover, by initially pausing the GIFs, your content will load faster. This control over animation provides users with the flexibility to halt it when necessary, enabling them to focus on the content and interact with it at their own pace.

This tutorial will guide you through the process of adding play and stop buttons for all gifs on your posts. Initially, the GIF will show its first frame as a preview, then when you click the play button, the GIF will start playing until you click the stop button. And when you click the play button again, the animation will resume where it’s left before.

Adding Play and Stop Buttons for GIF Animation

Step 1: Add the Custom Code

The initial phase entails integrating custom code to include play and stop buttons for GIFs in your posts. It’s highly recommended to create a backup of your WordPress files beforehand, utilizing backup plugins or the built-in backup feature provided by your hosting service.

Begin the process by navigating to the Appearance → Theme File Editor from your WordPress admin dashboard. Select the functions.php file from the Theme File list and paste the following code at the bottom of the file.

Note: For block themes, locate the Theme File Editor in the Tools menu. If your theme, such as “Twenty Twenty Three,” lacks the functions.php file, create it initially through SFTP or you can opt for a safer approach.

function wpp_gifs_output($content) {
    global $post;

    // Check if in single post and post type is post
    if (is_single() && $post->post_type === 'post') {
        // Find all GIF images
        $content = preg_replace_callback(
            '/<img[^>]+src=[\'"]([^\'"]+.gif)[\'"][^>]*>/i',
            'wrap_gif_in_controls',
            $content
        );
    }

    return $content;
}
add_filter('the_content', 'wpp_gifs_output');

function wrap_gif_in_controls($matches) {
    $gif_url = $matches[1];

    // Get first frame for preview image
    $preview_src = get_first_gif_frame($gif_url);

    return '<div class="gif-container">
                <img src="' . $preview_src . '" data-gif-url="' . $gif_url . '" class="gif-preview" alt="">
                <button id="gif-control-button" class="gif-play-button">Play GIF</button>
            </div>';
}

// Function to grab first frame of GIF
function get_first_gif_frame($gif_url) {
    $ch = curl_init($gif_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $gif_data = curl_exec($ch);
    curl_close($ch);

    // Extract first frame using GD library
    if (function_exists('imagecreatefromstring')) {
        $image = imagecreatefromstring($gif_data);
        ob_start();
        imagegif($image);
        $preview_data = ob_get_clean();
        imagedestroy($image);
        return 'data:image/gif;base64,' . base64_encode($preview_data);
    } else {
        // Alternative option: Use third-party library or placeholder image
        return 'placeholder.jpg'; // Replace with your placeholder image
    }
}

function enqueue_gif_controls_script() {
    wp_enqueue_script('gif-controls-script', get_template_directory_uri() . '/js/gif-controls.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_gif_controls_script');

function wpp_gif_control_js() {
  ?>
<script>
jQuery(document).ready(function($) {
    $('.gif-container').each(function() {
        var $container = $(this);
        var $previewImage = $container.find('.gif-preview');
        var $gifImage = $('<img>').attr('src', $previewImage.data('gif-url')).addClass('gif-image');
        var $playButton = $container.find('#gif-control-button');

        $previewImage.after($gifImage);
        $gifImage.hide(); // Initially hide GIF

        $playButton.click(function() {
            if ($gifImage.is(':visible')) { 
                $gifImage.hide();
                $previewImage.show();
                $(this).text('Play GIF');
                $(this).removeClass('gif-stop-button'); 
		$(this).addClass('gif-play-button');
            } else {
                $gifImage.show();
                $previewImage.hide();
                $(this).text('Stop GIF');
		$(this).removeClass('gif-play-button');
                $(this).addClass('gif-stop-button'); 
            }
        });
    });
});
</script>
  <?php
}
add_action('wp_footer', 'wpp_gif_control_js');

The provided code snippet adds play/pause controls to GIFs displayed in single blog posts on a WordPress site. It works by:

  1. Identifying GIFs: Finding all <img> tags with .gif URLs in single posts.
  2. Wrapping in container: Surrounding each GIF with a container holding a preview image and a play button.
  3. Extracting first frame: Using PHP’s GD library (if available) or a placeholder image for the preview.
  4. Adding JavaScript: Enqueuing a script that shows/hides the actual GIF on clicking the button and updates its text and class.

Once the code is properly positioned, click the Update File button to implement it.

Step 2: Add the Custom CSS

The subsequent step involves adding Custom CSS to initially hide the actual GIF and define the button position on top of the GIF, along with its styling. Below is the custom CSS:

.gif-container {
  position: relative;
  display: inline-block;
}

.gif-preview,
.gif-image {
  width: 100%; 
  height: auto;
}

.gif-preview {
  /* Styles for the preview image */
  border: 1px solid #ccc; /* Example border */
  cursor: pointer; /* Indicate clickability */
}

.gif-play-button,
.gif-stop-button {
  /* Common styles for both buttons */
  position: absolute;
  padding: 5px 10px; /* Adjust padding as needed */
  border: none; /* Remove default border */
  border-radius: 5px; /* Add rounded corners */
  cursor: pointer; /* Indicate clickable elements */
  font-size: 14px; /* Adjust font size as needed */
}

/* Specific styles for the play button */
.gif-play-button {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* Center the button */
  background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent background */
  color: white; /* White text */
}

/* Specific styles for the stop button */
.gif-container .gif-stop-button { 
  top: 10px;
  right: 10px;
  background-color: red;
  color: white;
}

/* Additional optional styles */
.gif-stop-button {
  /* Example: Increase size or change opacity */
  transform: scale(1);
  opacity: 0.8;
}

/* Hide the GIF image initially */
.gif-image {
  display: none;
}
    

To implement this, you can utilize the WordPress Customizer. Typically, you can access this customization area by navigating to Appearance and selecting Customize from the menu on your WordPress dashboard. Then, click on the Additional CSS block to open the CSS editor.

If you’re using a block theme, we have a separate article on how to enable the theme customizer specifically for block themes. Once you’ve added your custom CSS, remember to click the Publish button to activate the changes.

Step 3: See the Result

At this point, all GIFs in your posts will initially pause playback and display a play button overlay. Clicking the play button will activate the GIF’s animation, which will continue to loop until you click the stop button. Below is an illustration of the result.

The Bottom Line

Improve user engagement and loading times on your website by implementing play and stop buttons for GIF animations. This feature grants users control over the animation, enabling them to pause and resume at will, enhancing focus on content while offering a more interactive browsing experience.

This page may contain affiliate links, which help support our project. Read our affiliate disclosure.
Hendri Risman

Hendri Risman

Hendri is a WordPress expert and a writer staff at WPPagebuilders. He writes solutions on how to get things fixed in WordPress a lot. Mostly without involving a plugin.
Want to save yearly expense up to $219? why not?

Leave a Comment