Code Snippets that will accelerate your workflow!

Do you like our snippets and want to know when we add more free ones to the site? Just enter your email below and we’ll let you know when we create more awesomeness for you to use in your website projects!

By clicking Sign Up you’re confirming that you agree with our Terms and Conditions.

Featured Snippets

Unsplash Media Search

				
					/**
 * Plugin Name: Unsplash Media Integration
 * Author: Mark Harris
 * Version: 1.3
 * Description: Fetch, display and download images from Unsplash into your WordPress site.
 * Author URI: https://www.christchurchwebsolutions.co.uk
 *
 * Instructions to Obtain Unsplash API Key:
 * 1. Create an Unsplash developer account if you don’t already have one: https://unsplash.com/developers
 * 2. Log in and visit https://unsplash.com/oauth/applications
 * 3. Click "New Application", check all the agreement boxes, and click "Accept terms".
 * 4. Fill out the application name and description, then click "Create application".
 * 5. Scroll down to "Keys" and copy the "Access Key".
 * 6. Add your API Key to the box on the admin page and hit save.
 */

// Add a custom menu item to the WordPress admin menu
function unsplash_media_menu()
{
    add_menu_page(
        "Unsplash Media",
        "Unsplash Media",
        "manage_options",
        "unsplash-media",
        "unsplash_media_page"
    );
    add_action("admin_head", "unsplash_media_custom_css_js");
}
add_action("admin_menu", "unsplash_media_menu");
add_action("admin_init", "unsplash_api_settings");

function unsplash_api_settings()
{
    register_setting("unsplash-api-settings", "unsplash_api_key");
}

// The API key is now retrieved from the WordPress options table

// Enqueue custom CSS and JS for grid, image resizing, and AJAX handling
function unsplash_media_custom_css_js()
{
    ?>
    
        .unsplash-images {
            /* Masonry grid setup */
            column-count: 2;
            column-gap: 10px;
        }

        @media (min-width: 600px) {
            .unsplash-images {
                column-count: 3;
            }
        }

        @media (min-width: 1000px) {
            .unsplash-images {
                column-count: 6;
            }
        }

        .unsplash-image {
            /* Prevent images from being split across columns */
            break-inside: avoid;
            margin-bottom: 10px;
            position: relative; /* Added for positioning the download button */
        }

        .unsplash-image img {
            width: 100%;
            height: auto;
            display: block;
        }

        .download-button {
            position: absolute;
            bottom: 10px;
            left: 10px;
            padding: 5px 10px;
            background-color: #0073e6;
            color: #fff;
            border: none;
            cursor: pointer;
            z-index: 1;
            text-decoration: none;
            font-weight: bold;
        }

        .download-size {
            position: absolute;
            bottom: 40px;
            left: 10px;
            z-index: 1;
            margin-bottom: 10px;
        }

        .unsplash-search-container {
            margin-bottom: 20px; /* Space between search and image grid */
        }

        .unsplash-search-container input[type="text"] {
            padding: 8px;
            font-size: 14px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
        }

        .unsplash-search-container button {
            padding: 10px 15px;
            background-color: #0073e6;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .unsplash-search-container button:hover {
            background-color: #0056b3;
        }

        #load-more {
            display: block; /* Centering the button */
            margin: 20px auto; /* Space above and center alignment */
            padding: 10px 20px;
            font-size: 16px;
            background-color: #0073e6;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        #load-more:hover {
            background-color: #0056b3;
        }

        .unsplash-search-container select {
            padding: 8px; /* Match the padding of the input */
            font-size: 14px; /* Match the font size of the input */
            border: 1px solid #ddd; /* Border color to match the input */
            border-radius: 4px; /* Match the border-radius of the input */
            background-color: white; /* Background color to match the input */
            cursor: pointer; /* Cursor to indicate it's clickable */
            margin-right: 10px; /* Add space between the dropdown and the button */
            width: auto; /* Set the width to auto to accommodate content */
            min-width: 150px; /* Minimum width to make the dropdown wider */
        }

        /* Add custom arrow image and styling for non-IE browsers */
        .unsplash-search-container select {
            -webkit-appearance: none; /* Remove the default style in WebKit browsers */
            -moz-appearance: none; /* Remove the default style in Firefox */
            appearance: none; /* Remove the default style in modern browsers */
            background-image: url('data:image/svg+xml;charset=US-ASCII,');
            background-repeat: no-repeat;
            background-position: right 10px center; /* Position the arrow on the right */
            background-size: 12px; /* Size of the arrow */
        }

        /* Hover effect for the select element */
        .unsplash-search-container select:hover {
            border-color: #ccc; /* Slightly darker border on hover */
        }

        /* Focus effect for the select element */
        .unsplash-search-container select:focus {
            border-color: #0073e6; /* Match the focus border of the input */
            outline: none; /* Remove the default focus outline */
        }
    
    
        jQuery(document).ready(function ($) {
            // Function to load images from Unsplash
            function loadUnsplashImages(page) {
                var query = $('input[name="unsplash_query"]').val();
                var orientation = $('select[name="orientation"]').val(); // Get the orientation value

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'fetch_unsplash_images',
                        query: query,
                        page: page,
                        orientation: orientation // Include orientation in the data sent
                    },
                    success: function (response) {
                        if (response.success) {
                            if (page === 1) {
                                $('#unsplash-images').html(response.data.html);
                            } else {
                                $('#unsplash-images').append(response.data.html);
                            }
                            $('#load-more').show();
                        } else {
                            alert('Failed to load images.');
                        }
                    },
                    error: function() {
                        alert('An error occurred while loading images.');
                    }
                });
            }

            // Event handler for the search button
            $('#search_unsplash').click(function (e) {
                e.preventDefault();
                $('input[name="page"]').val(1);
                loadUnsplashImages(1);
            });

            // Event handler for the load more button
            $('#load-more').click(function () {
                var nextPage = parseInt($('input[name="page"]').val(), 10) + 1;
                $('input[name="page"]').val(nextPage);
                loadUnsplashImages(nextPage);
            });

            // Event handler for the download button
            $(document).on('click', '.download-button', function (e) {
                e.preventDefault();
                var selectedSizeUrl = $(this).prev('.download-size').val();
                var imageName = $(this).data('name');

                window.location.href = ajaxurl + '?action=download_unsplash_image&image_url=' + encodeURIComponent(selectedSizeUrl) + '&image_name=' + encodeURIComponent(imageName);
            });
        });
    
    results) || count($data->results) === 0) {
        wp_send_json_error("No images found on Unsplash for the given query.");
        wp_die();
    }

    $html = "";
    foreach ($data->results as $result) {
        $low_res_image_url = $result->urls->small; // Thumbnail for display
        $full_res_image_url = $result->urls->full; // Full-size image for download

        $image_description = $result->description ?: "unsplash-image"; // Using description as the filename
        $filename = sanitize_file_name($image_description) . ".jpg"; // Sanitize and append .jpg extension

        $html .= '<div class="unsplash-image">';
        $html .=
            '<img decoding="async" src="' .
            esc_url($low_res_image_url) .
            '" alt="' .
            esc_attr($image_description) .
            '">';
        $html .=
            'urls-&gt;full .
            '"&gt;Fullurls-&gt;regular .
            '"&gt;Regularurls-&gt;small .
            '"&gt;Small';
        $html .=
            '<a href="#" class="download-button" data-name="' .
            $filename .
            '">Download</a>';
        $html .= "</div>";
    }

    wp_send_json_success(["html" =&gt; $html]);
}
add_action("wp_ajax_fetch_unsplash_images", "fetch_unsplash_images");

// Server-side script to handle image download
function download_unsplash_image()
{
    if (!isset($_GET["image_url"]) || !isset($_GET["image_name"])) {
        wp_die("Image URL or name is missing.");
    }

    $image_url = sanitize_text_field($_GET["image_url"]);
    $image_name = sanitize_file_name($_GET["image_name"]);

    // Ensure the filename ends with .jpg
    if (substr($image_name, -4) !== ".jpg") {
        $image_name .= ".jpg";
    }

    $response = wp_safe_remote_get($image_url);
    if (is_wp_error($response)) {
        wp_die("Unable to download the image.");
    }

    $image_data = wp_remote_retrieve_body($response);

    // Create a temporary file with a .jpg extension
    $temp_file = tempnam(sys_get_temp_dir(), 'IMG') . '.jpg';
    file_put_contents($temp_file, $image_data);

    // Securely set headers
    header("Content-Description: File Transfer");
    header("Content-Type: image/jpeg");
    header('Content-Disposition: attachment; filename="' . $image_name . '"');
    header("Expires: 0");
    header("Cache-Control: must-revalidate");
    header("Pragma: public");
    header("Content-Length: " . filesize($temp_file));

    // Read and delete the temporary file
    readfile($temp_file);
    unlink($temp_file);

    exit();
}


add_action("wp_ajax_download_unsplash_image", "download_unsplash_image");
add_action("wp_ajax_nopriv_download_unsplash_image", "download_unsplash_image");

// Create the Unsplash Media page content
function unsplash_media_page()
{
    ?&gt;
    <div class="wrap">
    <h2>Unsplash Media</h2>
    
        
        
        <table class="form-table">
            <tr valign="top">
                <th scope="row">Unsplash API Key</th>
                <td>
                    &lt;input type=&quot;password&quot; name=&quot;unsplash_api_key&quot; value=&quot;" /&gt;
                </td>
            </tr>
        </table>
        
    
    <div class="unsplash-search-container">
        
            
            
                All
                Landscape
                Portrait
            
            <button type="submit" id="search_unsplash">Search</button>
            
        
    </div>
    <div id="unsplash-images" class="unsplash-images"></div>
    <button id="load-more">Load More</button>
</div>
    &lt;?php
}

// Localize the AJAX URL for the admin area
function localize_ajax_url()
{
    echo &#039;var ajaxurl = "' .
        admin_url("admin-ajax.php") .
        '";';
}
add_action("admin_head", "localize_ajax_url");

				
			
A snippet that adds an admin page to allow you to search for and download Unsplash Images in three sizes. You need an Unsplash API Key.

Elementor Container Links

				
					/**
 * This script adds click and keyboard event handlers to HTML containers with specific class names,
 * redirecting users to predefined URLs when these containers are clicked or when they are focused and the Enter key is pressed.
 * 
 * Usage:
 * 1. Replace 'container-class-1', 'container-class-2', 'container-class-3' with the actual
 *    class names of your HTML containers.
 * 2. Replace 'placeholder-url-1', 'placeholder-url-2', 'placeholder-url-3' with the actual
 *    URLs you want to associate with each container class.
 * 
 * Limitations:
 * - Make sure that the specified container classes exist in your HTML.
 * - The containers must be present in the DOM when this script is executed.
 * - This script assumes that the containers have a 'cursor: pointer' style to indicate they are clickable.
 * - It doesn't handle cases where multiple containers have the same class.
 */

document.addEventListener('DOMContentLoaded', function() {
    // Define the mappings of container classes to URLs
    var linkMappings = {
        'container-class-1': 'placeholder-url-1',
        'container-class-2': 'placeholder-url-2',
        'container-class-3': 'placeholder-url-3'
    };

    // Function to add click and keyboard event handlers to a container
    function addLinkToContainer(containerClass, url) {
        var container = document.querySelector('.' + containerClass);
        if (container) {
            container.style.cursor = 'pointer';

            // Click event handler
            container.addEventListener('click', function() {
                navigateToUrl(url);
            });

            // Keyboard event handler
            container.addEventListener('keydown', function(event) {
                if (event.key === 'Enter') {
                    navigateToUrl(url);
                }
            });

            // Make the container focusable
            container.setAttribute('tabindex', '0');
        }
    }

    // Function to navigate to a URL
    function navigateToUrl(url) {
        window.location.href = url;
    }

    // Loop through each mapping and apply the function
    for (var containerClass in linkMappings) {
        if (linkMappings.hasOwnProperty(containerClass)) {
            addLinkToContainer(containerClass, linkMappings[containerClass]);
        }
    }
});
				
			
Avatar
ThrudUK
Offline
Not currently playing any game.