Hide Images in Wordpress



 Php for hide post content image

<?php
// WPCode: Remove <img> tags from post content and replace with alt text (if present).
add_filter('the_content', function($content) {
    // Use DOMDocument to avoid brittle regex
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    // ensure proper encoding
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

    $imgs = $dom->getElementsByTagName('img');
    // collect nodes to remove (can't remove while iterating live)
    $toRemove = [];
    foreach ($imgs as $img) {
        $alt = $img->getAttribute('alt');
        $placeholder_text = $alt ? htmlspecialchars($alt) : ''; // keep alt as visible text optionally
        // create a text node (or nothing) to replace the image
        $textNode = $dom->createTextNode($placeholder_text);
        $toRemove[] = ['img' => $img, 'text' => $textNode];
    }
    foreach ($toRemove as $item) {
        $img = $item['img'];
        $textNode = $item['text'];
        $img->parentNode->replaceChild($textNode, $img);
    }
    $html = $dom->saveHTML();
    // remove the fake xml encoding wrapper
    $html = preg_replace('/^<\?xml.*?\?>/','',$html);
    return $html;
});
?>

php code remove featured image

<?php
// Disable post thumbnails (stop theme from generating featured images)
add_filter('post_thumbnail_html', '__return_empty_string', 10, 5);
add_filter('get_the_post_thumbnail', '__return_empty_string', 10, 5);
?>

css code

/* Hide all <img> visually for non-logged-in users */
body:not(.logged-in) img { display: none !important; }

/* hide background images too (for many themes) */
body:not(.logged-in) [style*="background-image"], body:not(.logged-in) .has-background {
    background-image: none !important;
}


No comments:

Post a Comment

Pages