web-dev-qa-db-ja.com

記事のすべての画像にクラスを動的に追加する

記事のすべての画像にクラスを追加するプラグインを作成しようとしています。これまでのところ、私は次のコードを持っています:

<?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;
        // Find images and add a class
    }
?>

しかし、コンテンツ内の画像を検索してクラスを追加する方法には行き詰まっています。また、画像にはすでにクラスが含まれている場合があります。その場合は、既存のクラスに新しいクラスを追加します。

編集:
特定のクラスで画像に透かしを入れるプラグインがありますが、サイトにはすでに多くの画像があるため、各クラスを経由するのではなく、画像にクラスを動的に追加したいと思います<img>タグをサイトに追加し、クラスを追加します。

CSSですべての画像をターゲットにできることは知っていますが、この場合は役に立ちません。

5
Bogowoe

コンテンツをDOMDocument()にロードして操作できます。

<?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;
        // Find images and add a class
        $dom = new DOMDocument();
        @$dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
        $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 you want to add
            $new_class          = ' yourclass';
            // the existing classes plus the new class
            $class_names_to_add = $existing_classes . $new_class;
            $image->setAttribute('class', $class_names_to_add);
        }
        // $dom now contains a complete HTML source, remove unnecessary tags
        $content = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
        return true;
    }
}
?>
3
johanpw

なぜこれをしたいのですか?

プラグインを使用せずにcssを使用して記事内のすべての画像を簡単にターゲティングできます。必要なのは少しのcssだけです。

.view-article img { // My awesome styles here ;}

記事内のすべての画像を対象とし、プラグインのようにオーバーヘッドや複雑さを追加しません。最も単純な方法が常に最良の方法です。

保守可能、スケーラブル、安全。

4
Seth Warburton