使用PHP为Joomla文章中的所有图像添加CSS类


Add CSS class to all images in Joomla articles using PHP

我已经安装了一个名为Nice Watermark的插件(在我的Joomla 3网站上),该插件将水印添加到具有特定类(在我的情况下是<img class="waterm" src="/images/wm/idx-homepage3cfotoby0.jpg" alt="">)的所有图像

是否有可能使用PHP添加一个CSS类的所有图像之前,网站加载?或者更好的是,只针对文章的一部分图像(我不想水印图标和其他模板图像)?

我在想一个插件,在代码中找到<img src=.../>标签并添加一个类,但我不确定如何解决这个问题。

也许有人能给我指个方向?

编辑:

我用下面的代码创建了一个Joomla插件,它可以工作,但它也在图像周围添加了一个完整的html结构(<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body><p><img...)。我怎样才能避免这种情况呢?

<?php
// no direct access
defined('_JEXEC') or die;
jimport('joomla.plugin.plugin');
class plgContentAddImageClass extends JPlugin
{
    public function __construct(&$subject, $params)
    {
        parent::__construct($subject, $params);
    }
    public function onContentPrepare($context, &$article, &$params, $offset = 0)
    {
        $content =& $article->text; // Article content
        $dom = new DOMDocument();
        @$dom->loadHTML($content);
        $dom->preserveWhiteSpace = false;
        $images                  = $dom->getElementsByTagName('img');
        foreach($images as $image) {
            // the existing classes already on the images
            $existing_classes   = $image->getAttribute('class');
            // the class we're adding
            $new_class          = ' watermark';
            // the existing classes plus the new class
            $class_names_to_add = $existing_classes . $new_class;
            $image->setAttribute('class', $class_names_to_add);
        }
        $content = $dom->saveHTML();
        return true;
    }
}
?>

根据PHP手册,saveHTML()方法自动将<html>, <body><!doctype>标记添加到输出中,但我在同一页面上发现了删除这些代码的代码片段。下面是为我工作的完整代码:

<?php
// no direct access
defined('_JEXEC') or die;
jimport('joomla.plugin.plugin');
class plgContentAddImageClass extends JPlugin
{
    public function __construct(&$subject, $params)
    {
        parent::__construct($subject, $params);
    }
    public function onContentPrepare($context, &$article, &$params, $offset = 0)
    {
        // Article Content
        $content = &$article->text;
        $dom = new DOMDocument();
        @$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
        $dom->preserveWhiteSpace = false;
        $images                  = $dom->getElementsByTagName('img');
        foreach($images as $image) {
            $existing_classes   = $image->getAttribute('class');
            // the class we're adding
            $new_class          = ' watermark';
            // the existing classes plus the new class
            $class_names_to_add = $existing_classes . $new_class;
            $image->setAttribute('class', $class_names_to_add);
        }
        // Remove unwanted tags
        $content = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
        return true;
    }
}
?>