prüfen auf welchen Seiten ein Image eingebunden ist

Estimated reading: 5 minutes 245 views

Wer kennt das nicht. Die Mediathek ist am überquellen und man weiß nicht ob die Grafik überhaupt noch irgendwo gebraucht wird. Hier greift dieses kleine Script.

Es zeigt dir in der Detail Ansicht des Bildes rechts unten zwei neue Buttons an.

Bilderverwendung: [Verwendung prüfen] [Bild löschen]

// 1. AJAX Handler Registrierungen
add_action('wp_ajax_check_image_usage', 'check_image_usage_ajax');
add_action('wp_ajax_delete_image', 'delete_image_ajax');

// 2. Medienfeld hinzufügen
function add_image_usage_to_media($form_fields, $post) {
    // Nonces für Sicherheit
    $check_nonce = wp_create_nonce('check_image_usage_nonce');
    $delete_nonce = wp_create_nonce('delete_image_nonce');
    
    $output = '<div class="image-usage-container">';
    $output .= '<div id="usage-results-' . esc_attr($post->ID) . '"></div>';
    $output .= '<div style="margin-top: 10px; display: flex; gap: 10px; align-items: center;">';
    $output .= '<button type="button" class="button button-secondary check-usage" data-id="' . esc_attr($post->ID) . '">Verwendung prüfen</button>';
    $output .= '<button type="button" class="button button-link-delete" style="color: #dc3232;" data-id="' . esc_attr($post->ID) . '">Bild löschen</button>';
    $output .= '<span class="spinner" style="float: none; margin: 0;"></span>';
    $output .= '</div>';
    $output .= '</div>';

    // Javascript
    $output .= "<script>
    jQuery(document).ready(function($) {
        $('.check-usage').on('click', function() {
            var button = $(this);
            var resultDiv = $('#usage-results-' + button.data('id'));
            var spinner = button.parent().find('.spinner');
            
            button.prop('disabled', true);
            spinner.css('visibility', 'visible');
            resultDiv.html('Suche läuft...');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'check_image_usage',
                    image_id: button.data('id'),
                    nonce: '" . $check_nonce . "'
                },
                success: function(response) {
                    if(response.success) {
                        resultDiv.html(response.data);
                    } else {
                        resultDiv.html('Fehler: ' + response.data);
                    }
                },
                error: function(xhr, status, error) {
                    resultDiv.html('Fehler bei der Suche');
                },
                complete: function() {
                    button.prop('disabled', false);
                    spinner.css('visibility', 'hidden');
                }
            });
        });

        $('.button-link-delete').on('click', function() {
            if (!confirm('Möchten Sie dieses Bild wirklich löschen?')) {
                return;
            }
            var button = $(this);
            var spinner = button.parent().find('.spinner');
            
            button.prop('disabled', true);
            spinner.css('visibility', 'visible');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'delete_image',
                    image_id: button.data('id'),
                    nonce: '" . $delete_nonce . "'
                },
                success: function(response) {
                    if(response.success) {
                        window.location.reload();
                    } else {
                        alert('Fehler beim Löschen: ' + response.data);
                    }
                },
                error: function() {
                    alert('Fehler beim Löschen');
                },
                complete: function() {
                    button.prop('disabled', false);
                    spinner.css('visibility', 'hidden');
                }
            });
        });
    });
    </script>";
    
    $form_fields['image_usage'] = array(
        'label' => 'Bildverwendung',
        'input' => 'html',
        'html'  => $output
    );
    
    return $form_fields;
}
add_filter('attachment_fields_to_edit', 'add_image_usage_to_media', 10, 2);

// 3. Handler-Funktionen
function check_image_usage_ajax() {
    // Sicherheitscheck
    if (!check_ajax_referer('check_image_usage_nonce', 'nonce', false)) {
        wp_send_json_error('Sicherheitscheck fehlgeschlagen');
    }

    if (!isset($_POST['image_id'])) {
        wp_send_json_error('Keine Bild-ID angegeben');
    }

    $image_id = intval($_POST['image_id']);
    $found_usage = array();
    global $wpdb;

    // 1. Suche in post_content
    $url = wp_get_attachment_url($image_id);
    if (!$url) {
        wp_send_json_error('Bild nicht gefunden');
    }

    $filename = basename($url);
    
    $results = $wpdb->get_results($wpdb->prepare(
        "SELECT DISTINCT ID, post_title, post_type 
        FROM {$wpdb->posts} 
        WHERE (post_content LIKE %s OR post_content LIKE %s)
        AND post_status = 'publish'",
        '%' . $wpdb->esc_like($url) . '%',
        '%' . $wpdb->esc_like($filename) . '%'
    ));

    if ($results) {
        $found_usage['content'] = $results;
    }

    // 2. Suche nach Featured Images
    $featured_results = $wpdb->get_results($wpdb->prepare(
        "SELECT post_id 
        FROM {$wpdb->postmeta} 
        WHERE meta_key = '_thumbnail_id' 
        AND meta_value = %d",
        $image_id
    ));

    if ($featured_results) {
        $found_usage['featured'] = $featured_results;
    }

    // 3. Überprüfe die "Hochgeladen zu" Beziehung
    $parent_id = get_post($image_id)->post_parent;
    if ($parent_id) {
        $found_usage['parent'] = array(get_post($parent_id));
    }

    // Ausgabe erstellen
    $output = '<div style="margin-top: 10px;">';
    
    if (empty($found_usage)) {
        $output .= '<p>Keine Verwendung gefunden</p>';
    } else {
        // Parent Post
        if (!empty($found_usage['parent'])) {
            $output .= '<strong>Hochgeladen zu:</strong><ul style="margin-left: 20px; list-style: disc;">';
            foreach ($found_usage['parent'] as $post) {
                if ($post) {
                    $output .= sprintf(
                        '<li><a href="%s">%s</a> (%s)</li>',
                        get_edit_post_link($post->ID),
                        esc_html($post->post_title),
                        esc_html($post->post_type)
                    );
                }
            }
            $output .= '</ul>';
        }

        // Content Usage
        if (!empty($found_usage['content'])) {
            $output .= '<strong>Verwendet im Inhalt:</strong><ul style="margin-left: 20px; list-style: disc;">';
            foreach ($found_usage['content'] as $post) {
                $output .= sprintf(
                    '<li><a href="%s">%s</a> (%s)</li>',
                    get_edit_post_link($post->ID),
                    esc_html($post->post_title),
                    esc_html($post->post_type)
                );
            }
            $output .= '</ul>';
        }

        // Featured Images
        if (!empty($found_usage['featured'])) {
            $output .= '<strong>Verwendet als Featured Image:</strong><ul style="margin-left: 20px; list-style: disc;">';
            foreach ($found_usage['featured'] as $result) {
                $post = get_post($result->post_id);
                if ($post) {
                    $output .= sprintf(
                        '<li><a href="%s">%s</a> (%s)</li>',
                        get_edit_post_link($post->ID),
                        esc_html($post->post_title),
                        esc_html($post->post_type)
                    );
                }
            }
            $output .= '</ul>';
        }
    }
    
    $output .= '</div>';
    
    wp_send_json_success($output);
}

function delete_image_ajax() {
    // Sicherheitscheck
    if (!check_ajax_referer('delete_image_nonce', 'nonce', false)) {
        wp_send_json_error('Sicherheitscheck fehlgeschlagen');
    }

    if (!isset($_POST['image_id'])) {
        wp_send_json_error('Keine Bild-ID angegeben');
    }

    $image_id = intval($_POST['image_id']);

    // Prüfe Berechtigungen
    if (!current_user_can('delete_posts')) {
        wp_send_json_error('Keine Berechtigung');
    }

    // Lösche das Bild
    $result = wp_delete_attachment($image_id, true);

    if ($result) {
        wp_send_json_success('Bild erfolgreich gelöscht');
    } else {
        wp_send_json_error('Fehler beim Löschen des Bildes');
    }
}

prüfen auf welchen Seiten ein Image eingebunden ist