DEV Community

Vague Graf
Vague Graf

Posted on

Building a Zero-Dependency Image Like Button in WordPress (AJAX + Post Meta)

Most WordPress rating plugins create extra database tables, load heavy jQuery dependencies, and slow down page rendering—especially when you only need a simple Like button beneath individual images inside an article.

In this short tutorial, I will show how to build a lightweight (~4 KB), dependency-free image like system using native WordPress post_meta, admin-ajax.php, and vanilla JavaScript.

How It Works

  1. Automatic Image Detection: On page load, a lightweight script scans your main article container for images wider than 200px (ignoring avatars, headers, and navigation icons).
  2. Unique Key Generation: Each image gets a clean key derived from its filename, allowing readers to like individual photos within the same post.
  3. Instant UI + Persistent Storage: Clicking the button updates the counter immediately via localStorage and sends an asynchronous fetch request to WordPress to store the total count in wp_postmeta.

Full Implementation (wp-image-likes.php)

Paste the following snippet into your child theme's functions.php file (or add it through a snippet manager like WPCode):

<?php
if (!defined('ABSPATH')) {
    exit;
}

// 1. AJAX handler for saving and removing image likes in WordPress post meta
add_action('wp_ajax_wpil_toggle_img_like', 'wpil_handle_img_like');
add_action('wp_ajax_nopriv_wpil_toggle_img_like', 'wpil_handle_img_like');

function wpil_handle_img_like() {
    \$post_id     = isset(\(_POST['post_id']) ? intval(\)_POST['post_id']) : 0;
    \(img_key     = isset(\)_POST['img_key']) ? sanitize_key(\(_POST['img_key']) : '';\)action_type = isset(\(_POST['type']) ? sanitize_text_field(\)_POST['type']) : 'like';

    if (!\(post_id \vert{}\vert{} !\)img_key) {
        wp_send_json_error(array('message' => 'Invalid parameters.'));
    }

    \(meta_key = '_wpil_likes_' .\)img_key;
    \$count    = (int) get_post_meta(\(post_id,\)meta_key, true);

    if (\(action_type === 'like') {\)count++;
    } elseif (\$action_type === 'unlike' && \(count > 0) {\)count--;
    }

    update_post_meta(\$post_id, \(meta_key,\)count);
    wp_send_json_success(array('count' => \$count));
}

// 2. Render inline styles and frontend JavaScript in the footer
add_action('wp_footer', 'wpil_render_assets', 99);

function wpil_render_assets() {
    if (!is_singular()) {
        return;
    }

    \$post_id = get_queried_object_id();
    if (!\$post_id) {
        return;
    }

    \$all_meta   = get_post_meta(\(post_id);\)likes_data = array();

    if (\$all_meta) {
        foreach (\$all_meta as key => val) {
            if (strpos(\(key, '_wpil_likes_') === 0) {\)clean_key              = str_replace('_wpil_likes_', '', \(key);\)likes_data[\(clean_key] = is_array(\)val) ? (int) val : (int) val;
            }
        }
    }
    ?>
    <style>
        .img-like-bar {
            display: flex !important;
            justify-content: flex-start !important;
            align-items: center !important;
            width: 100% !important;
            margin: 10px 0 18px 0 !important;
            padding: 0 !important;
        }
        .img-like-btn {
            display: inline-flex !important;
            align-items: center !important;
            gap: 7px !important;
            padding: 7px 14px !important;
            margin: 0 !important;
            border: 1px solid rgba(128, 128, 128, 0.25) !important;
            border-radius: 999px !important;
            background: rgba(128, 128, 128, 0.08) !important;
            color: inherit !important;
            font-size: 13px !important;
            font-weight: 500 !important;
            line-height: 1 !important;
            cursor: pointer !important;
            transition: transform 0.2s ease, background 0.2s ease, border-color 0.2s ease, color 0.2s ease !important;
        }
        .img-like-btn:hover {
            background: rgba(128, 128, 128, 0.16) !important;
            border-color: rgba(128, 128, 128, 0.45) !important;
            transform: translateY(-1px) !important;
        }
        .img-like-btn svg {
            width: 15px !important;
            height: 15px !important;
            fill: transparent !important;
            stroke: currentColor !important;
            stroke-width: 2 !important;
        }
        .img-like-btn.is-liked {
            border-color: rgba(255, 71, 87, 0.55) !important;
            background: rgba(255, 71, 87, 0.12) !important;
            color: #ff4757 !important;
        }
        .img-like-btn.is-liked svg {
            fill: #ff4757 !important;
            stroke: #ff4757 !important;
            transform: scale(1.1) !important;
        }
        .img-like-count {
            font-weight: 600 !important;
        }
    </style>

    <script type="text/javascript">
    window.initWpImageLikes = function() {
        var targetSelectors  = 'main img, article img, .entry-content img, .post-content img';
        var excludeSelectors = 'header, footer, nav, .author-avatar, .post-author, .related-posts';
        var minImageWidth    = 200;

        var postId       = <?php echo intval(\$post_id); ?>;
        var initialLikes = <?php echo wp_json_encode(\$likes_data); ?>;
        var ajaxUrl      = "<?php echo esc_url(admin_url('admin-ajax.php')); ?>";
        var images       = document.querySelectorAll(targetSelectors);

        for (var i = 0; i < images.length; i++) {
            var img = images[i];
            if (img.getAttribute('data-like-ready') === '1') continue;
            if (excludeSelectors && img.closest(excludeSelectors)) continue;

            var rect = img.getBoundingClientRect();
            if (rect.width > 0 && rect.width < minImageWidth) continue;

            img.setAttribute('data-like-ready', '1');

            var rawSrc = img.getAttribute('data-src') || img.currentSrc || img.src || '';
            var qPos   = rawSrc.indexOf('?');
            if (qPos !== -1) rawSrc = rawSrc.substring(0, qPos);

            var fileName = rawSrc.substring(rawSrc.lastIndexOf('/') + 1);
            var imgKey   = fileName.replace(/[^a-zA-Z0-9]/g, '').slice(-24);
            if (!imgKey) imgKey = 'img' + i;

            var storageKey = 'wpil_liked_' + postId + '_' + imgKey;
            var anchorEl   = img.closest('a') || img;

            var bar = document.createElement('div');
            bar.className = 'img-like-bar';

            var currentCount = initialLikes[imgKey] ? initialLikes[imgKey] : 0;
            var isLiked      = window.localStorage.getItem(storageKey) === '1';

            var btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'img-like-btn' + (isLiked ? ' is-liked' : '');
            btn.innerHTML =
                '<svg viewBox="0 0 24 24"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>' +
                '<span class="img-like-label">' + (isLiked ? 'Liked' : 'Like') + '</span>' +
                '<span class="img-like-count">' + (currentCount > 0 ? currentCount : '') + '</span>';

            (function(b, k, sKey) {
                b.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();

                    var likedNow   = b.classList.contains('is-liked');
                    var actionType = likedNow ? 'unlike' : 'like';
                    var countSpan  = b.querySelector('.img-like-count');
                    var labelSpan  = b.querySelector('.img-like-label');
                    var num        = parseInt(countSpan.textContent ? countSpan.textContent : '0', 10);

                    if (likedNow) {
                        b.classList.remove('is-liked');
                        window.localStorage.removeItem(sKey);
                        labelSpan.textContent = 'Like';
                        num = Math.max(0, num - 1);
                    } else {
                        b.classList.add('is-liked');
                        window.localStorage.setItem(sKey, '1');
                        labelSpan.textContent = 'Liked';
                        num += 1;
                    }
                    countSpan.textContent = num > 0 ? num : '';

                    var formData = new FormData();
                    formData.append('action', 'wpil_toggle_img_like');
                    formData.append('post_id', postId);
                    formData.append('img_key', k);
                    formData.append('type', actionType);

                    fetch(ajaxUrl, { method: 'POST', body: formData })
                        .then(function(res) { return res.json(); })
                        .then(function(data) {
                            if (data && data.success) {
                                countSpan.textContent = data.data.count > 0 ? data.data.count : '';
                            }
                        });
                });
            })(btn, imgKey, storageKey);

            bar.appendChild(btn);
            if (anchorEl.parentNode) {
                anchorEl.parentNode.insertBefore(bar, anchorEl.nextSibling);
            }
        }
    };

    window.initWpImageLikes();
    setTimeout(window.initWpImageLikes, 1000);
    </script>
    <?php
}
Enter fullscreen mode Exit fullscreen mode

Customizing for Your Theme

You can adjust three variables inside initWpImageLikes() to fit any WordPress theme:

  • targetSelectors — containers where the script searches for content images.
  • excludeSelectors — elements to skip (author avatars, sidebars, related posts).
  • minImageWidth — minimum image width in pixels to attach a button.

Source Code

The full repository with installation notes and an MIT License is available on GitHub:

GitHub Repository: wp-image-likes

Top comments (0)