3 Minuten, 14 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>

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 :-)

urb.php Sourcecode

<?php
/**
 * Plugin Name: Unsplash Random Background (URB)
 * Description: Lädt ein zufälliges Bild aus einer Unsplash Collection und setzt es als Hintergrundbild
 * Version: 1.0
 * Author: PHOENIXSEO.de Frank Pfabigan e.K.
 */
// Verhindere direkten Zugriff
if (!defined('ABSPATH')) {
    exit;
}
class URB_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_enqueue_scripts'));
        add_action('admin_menu', array($this, 'urb_add_admin_menu'));
        add_action('admin_init', array($this, 'urb_register_settings'));
        add_action('wp_ajax_urb_get_random_unsplash', array($this, 'urb_get_random_unsplash'));
        add_action('wp_ajax_nopriv_urb_get_random_unsplash', array($this, 'urb_get_random_unsplash'));
    }
    public function urb_enqueue_scripts() {
        wp_enqueue_script('urb-background', plugins_url('js/urb.js', __FILE__), array('jquery'), '1.0', true);
        wp_localize_script('urb-background', 'urbAjax', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'collection_id' => get_option('urb_collection_id', $this->default_collection)
        ));
        wp_enqueue_style('urb-background', plugins_url('css/urb.css', __FILE__));
    }
    public function urb_add_admin_menu() {
        add_options_page(
            'URB Settings',
            'URB Settings',
            'manage_options',
            'urb-background',
            array($this, 'urb_create_admin_page')
        );
    }
    public function urb_register_settings() {
        register_setting('urb_settings', 'urb_api_key');
        register_setting('urb_settings', 'urb_collection_id');
    }
    public function urb_create_admin_page() {
        ?>
        <div class="wrap">
            <h2>(URB) 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"&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_settings');
                do_settings_sections('urb_settings');
                ?>
                <table class="form-table">
                    <tr>
                        <th>Unsplash API Key</th>
                        <td>
                            <input type="text" name="urb_api_key" 
                                   value="<?php echo esc_attr(get_option('urb_api_key')); ?>" 
                                   class="regular-text">
                        </td>
                    </tr>
                    <tr>
                        <th>Unsplash Collection ID</th>
                        <td>
                            <input type="text" name="urb_collection_id" 
                                   value="<?php echo esc_attr(get_option('urb_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_get_random_unsplash() {
        $api_key = get_option('urb_api_key');
        $collection_id = get_option('urb_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_RandomBackground();

/css/urb.css Sourcecode

#urb {
    position: relative;
    width: 100%;
    height: 100vh;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    transition: opacity 0.5s ease-in-out;
}
.urb-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-credits a {
    color: white;
    text-decoration: underline;
}
.urb-credits a:hover {
    color: #ddd;
}

/js/urb.js Sourcecode

jQuery(document).ready(function($) {
    function urbLoadRandomImage() {
        $.ajax({
            url: urbAjax.ajaxurl,
            type: 'POST',
            data: {
                action: 'urb_get_random_unsplash'
            },
            success: function(response) {
                if (response.success) {
                    const targetDiv = $('#urb');
                    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-credits">' +
                            'Foto von <a href="' + data.photo_link + '" target="_blank">' + 
                            data.photographer + '</a> auf Unsplash</div>');
                        targetDiv.find('.urb-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 (3 Wochen)
Content changed (vor 3 Wochen)
URL Path /blog/wordpress-plugin-urb
UUID e2e98a01-8222-4951-80e4-fd909cab129f