3 Minuten, 49 Sekunden ∅ Lesezeit @ 225 WPM

Ich hab meinen Blog-Artikel "Unsplash random background Image aus Kollektion Javascript" weitergesponnen und ein Wordpress Plugin mit dieser Funktionalität erstellt.

Einfach das Plugin runterladen, installieren und an gewünschter Stelle ein DIV mit der ID "urb" platzieren:

<div id="urb-div"></div>

In den Einstellungen den API Key von Unsplash eintragen (kostenloser Account), die gewünschte Kollektions-ID eintragen und das Plugin wählt zufällig eines der Bilder der Kollektion aus und stellt es als Hintergrund des DIVS dar.

Das DIV selbst kannst du einfach per CSS wie gewünscht anpassen.

Dies ist nur eine kleine Spielerei, die andere inspirieren soll, etwas Großartiges hieraus zu erschaffen.

Der gesamte Sourcecode ist hier aufgeführt. Zum Runterladen einfach zur Seite "Downloads" wechseln, da liegt das ganze als installationsbereites ZIP.

Viel Spaß damit :-)

Edit 19.03.2025:

Ich habe die Idee weiterentwickelt und das Plugin URB-Block programmiert, das nun einen richtigen Gutenberg-Block darstellt. Dieser stellt nicht nur das Hintergrundbild wie in URB-Div dar, sondern kann auch weitere Blöcke innerhalb von URB-Block anzeigen. Zudem sind viele Eigenschaften des Hintergrundbildes nun auch direkt im Editor konfigurierbar.

Zum Nachfolger URB-Block

URB-DIV
Wordpress Plugin

Platziere irgendwo ein <div id="urb-div"></div> und dann entfaltet sich dort ein zufälliges Hintergrundbild von unsplash.com (entweder gesamt oder aus deiner Collection ID). Du brauchst einen kostenlosen unsplash API Key.

Falls das Plugin dir gefällt und du es gebrauchen kannst, freue ich mich über ein bisschen Support:

Unterstütze mich mit einer kleinen Spende bei ko-fi.com

Sektor Icon

urb-div.php Sourcecode

<?php
/**
 * Plugin Name: URB-Div (Unsplash Random Background in a Div)
 * Description: Lädt ein zufälliges Bild aus einer Unsplash Collection und setzt es als Hintergrundbild
 * Plugin URI: https://phoenixseo.de/blog/wordpress-plugin-urb-div
 * Version: 1.0
 * Author: PHOENIXSEO.de Frank Pfabigan e.K.
 * Author URI: https://phoenixseo.de
 * Text Domain: urb-div
 * License: GPL v2 or later
 */

// Verhindere direkten Zugriff
if (!defined('ABSPATH')) {
    exit;
}

class URB_DIV_RandomBackground {
    private $api_key = ''; // Hier Ihren Unsplash API Key eintragen
    private $default_collection = '4759555'; // Standard Collection ID

    public function __construct() {
        add_action('wp_enqueue_scripts', array($this, 'urb_div_enqueue_scripts'));
        add_action('admin_menu', array($this, 'urb_div_add_admin_menu'));
        add_action('admin_init', array($this, 'urb_div_register_settings'));
        add_action('wp_ajax_urb_div_get_random_unsplash', array($this, 'urb_div_get_random_unsplash'));
        add_action('wp_ajax_nopriv_urb_div_get_random_unsplash', array($this, 'urb_div_get_random_unsplash'));
    }

    public function urb_div_enqueue_scripts() {
        wp_enqueue_script('urb-div-background', plugins_url('js/urb-div.js', __FILE__), array('jquery'), '1.0', true);
        wp_localize_script('urb-div-background', 'urbAjax', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'collection_id' => get_option('urb_div_collection_id', $this->default_collection)
        ));
        wp_enqueue_style('urb-div-background', plugins_url('css/urb-div.css', __FILE__));
    }

    public function urb_div_add_admin_menu() {
        add_options_page(
            'URB Div Settings',
            'URB Div Settings',
            'manage_options',
            'urb-div-background',
            array($this, 'urb_div_create_admin_page')
        );
    }

    public function urb_div_register_settings() {
        register_setting('urb_div_settings', 'urb_div_api_key');
        register_setting('urb_div_settings', 'urb_div_collection_id');
    }

    public function urb_div_create_admin_page() {
        ?>
        <div class="wrap">
            <h2>(URB-Div) Unsplash Random Background Einstellungen</h2>
            <p>Platziere an gewünschter Stelle einen Block mit "Individuellem HTML",
                mit folgendem Inhalt:</p>
            <pre>&lt;div id="urb-div"&gt;&lt;/div&gt;</pre>
            <p>Breite, Höhe und Aspekte des Hintergrunbilds kannst du einfach per CSS anpassen.</p>
            <form method="post" action="options.php">
                <?php
                settings_fields('urb_div_settings');
                do_settings_sections('urb_div_settings');
                ?>
                <table class="form-table">
                    <tr>
                        <th>Unsplash API Key</th>
                        <td>
                            <input type="text" name="urb_div_api_key" 
                                   value="<?php echo esc_attr(get_option('urb_div_api_key')); ?>" 
                                   class="regular-text">
                        </td>
                    </tr>
                    <tr>
                        <th>Unsplash Collection ID</th>
                        <td>
                            <input type="text" name="urb_div_collection_id" 
                                   value="<?php echo esc_attr(get_option('urb_div_collection_id', $this->default_collection)); ?>" 
                                   class="regular-text">
                            <p class="description">Die ID der Unsplash Collection, aus der die Bilder geladen werden sollen. 
                            Lassen Sie dieses Feld leer, um aus allen verfügbaren Bildern zu wählen.</p>
                        </td>
                    </tr>
                </table>
                <?php submit_button(); ?>
            </form>

            <p>Ein kleines WP Plugin von <a href="https://phoenixseo.de">PHOENIXSEO.de</a> Frank Pfabigan e.K.</p>
        </div>
        <?php
    }

    public function urb_div_get_random_unsplash() {
        $api_key = get_option('urb_div_api_key');
        $collection_id = get_option('urb_div_collection_id');
        
        if (empty($api_key)) {
            wp_send_json_error('API Key nicht konfiguriert');
            return;
        }

        if (!empty($collection_id)) {
            // Zuerst alle Bilder aus der Collection holen (maximal 30)
            $response = wp_remote_get(
                'https://api.unsplash.com/collections/' . $collection_id . '/photos?per_page=30',
                array(
                    'headers' => array(
                        'Authorization' => 'Client-ID ' . $api_key
                    )
                )
            );

            if (is_wp_error($response)) {
                wp_send_json_error('Fehler beim Laden der Collection');
                return;
            }

            $photos = json_decode(wp_remote_retrieve_body($response));
            
            if (empty($photos)) {
                wp_send_json_error('Keine Bilder in der Collection gefunden');
                return;
            }

            // Zufälliges Bild aus der Collection auswählen
            $random_photo = $photos[array_rand($photos)];
            
            wp_send_json_success(array(
                'url' => $random_photo->urls->regular,
                'photographer' => $random_photo->user->name,
                'photo_link' => $random_photo->links->html
            ));
        } else {
            // Wenn keine Collection ID angegeben ist, ein zufälliges Bild laden
            $response = wp_remote_get('https://api.unsplash.com/photos/random', array(
                'headers' => array(
                    'Authorization' => 'Client-ID ' . $api_key
                )
            ));

            if (is_wp_error($response)) {
                wp_send_json_error('Fehler beim Laden des Bildes');
                return;
            }

            $body = json_decode(wp_remote_retrieve_body($response));
            
            if (!empty($body->urls->regular)) {
                wp_send_json_success(array(
                    'url' => $body->urls->regular,
                    'photographer' => $body->user->name,
                    'photo_link' => $body->links->html
                ));
            } else {
                wp_send_json_error('Kein Bild gefunden');
            }
        }

        wp_die();
    }
}

// Plugin initialisieren
new URB_DIV_RandomBackground();

/css/urb-div.css Sourcecode

#urb-div {
    position: relative;
    width: 100%;
    height: 100vh;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    transition: opacity 0.5s ease-in-out;
}

.urb-div-credits {
    position: absolute;
    bottom: 10px;
    right: 10px;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 5px 10px;
    border-radius: 3px;
    font-size: 12px;
}

.urb-div-credits a {
    color: white;
    text-decoration: underline;
}

.urb-div-credits a:hover {
    color: #ddd;
}

/js/urb-div.js Sourcecode

jQuery(document).ready(function($) {
    function urbLoadRandomImage() {
        $.ajax({
            url: urbAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'urb_div_get_random_unsplash'
            },
            success: function(response) {
                if (response.success) {
                    const targetDiv = $('#urb-div');
                    const data = response.data;
                    
                    // Vorlade-Animation für das Bild
                    const img = new Image();
                    img.onload = function() {
                        targetDiv.css({
                            'background-image': 'url(' + data.url + ')',
                            'opacity': 0
                        }).animate({opacity: 1}, 500);
                        
                        // Credits hinzufügen
                        const credits = $('<div class="urb-div-credits">' +
                            'Foto von <a href="' + data.photo_link + '" target="_blank">' + 
                            data.photographer + '</a> auf Unsplash</div>');
                        targetDiv.find('.urb-div-credits').remove(); // Alte Credits entfernen
                        targetDiv.append(credits);
                    };
                    img.src = data.url;
                } else {
                    console.error('Fehler beim Laden des Bildes:', response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('Ajax Fehler:', error);
            }
        });
    }

    // Initial laden
    urbLoadRandomImage();

    // Optional: Neuladen alle 24 Stunden
    setInterval(urbLoadRandomImage, 24 * 60 * 60 * 1000);
});
Artikel-Nits-Referenz
Content created (2 Monate 3 Wochen)
Content changed (vor 4 Wochen 1 Tag)
URL Path /blog/wordpress-plugin-urb-div
UUID e2e98a01-8222-4951-80e4-fd909cab129f