プラグインでブロック内で使用するcms:idを追加する

ブロック内で使用するcms:idを追加するプラグインを作成してみます。

今回はプラグインの書き方で作成したplugin_baseプラグインに書き足す形で機能の追加を行います。


記事タイトルをmd5関数でハッシュ化した値を出力するcms:id="hash"を追加します。

PHP: md5 - Manual


/CMSインストールディレクトリ/common/site_include/plugin/plugin_base/plugin_base.php

<?php

class PluginBasePlugin{

	const PLUGIN_ID = "plugin_base";

	function getId(){
		return self::PLUGIN_ID;
	}

	function init(){
		CMSPlugin::addPluginMenu(self::PLUGIN_ID,array(
			"name" => "プラグインの基本構造",
			"type" => Plugin::TYPE_NONE,
			"description" => "",
			"author" => "",
			"url" => "",
			"mail" => "",
			"version" => "1.0"
		));
		
		// 当プラグインが有効であるかを調べる
		if(CMSPlugin::activeCheck(self::PLUGIN_ID)){
			if(defined("_SITE_ROOT_")){
				// 公開側ページの方で動作する拡張ポイントで使用したいものを追加する

				// 記事が呼び出される前の拡張ポイントを利用します。三番目の値の配列のonEntryOutputはプラグインのクラスに追加するメソッド名になります
				CMSPlugin::setEvent("onEntryOutput", self::PLUGIN_ID, array($this, "onEntryOutput"));
			
			}else{
				// 管理画面側の方で動作する拡張ポイントで使用したいものを追加する
			}
		}
	}

	// CMSPlugin::setEventで追加した拡張ポイントの処理のコードを書きます。
	function onEntryOutput($args){
		$entry = $args["entry"];
		$htmlObj = $args["SOY2HTMLObject"];

		$htmlObj->createAdd("hash", "HTMLLabel", array(
			"soy2prefix" => "cms",
			"text" => md5((string)$entry->getTitle())
		));
	}

	public static function register(){
		$obj = CMSPlugin::loadPluginConfig(self::PLUGIN_ID);
		if(!$obj) $obj = new PluginBasePlugin();
		CMSPlugin::addPlugin(self::PLUGIN_ID, array($obj, "init"));
	}
}

PluginBasePlugin::register();

プラグインで使用できる拡張ポイントについてはhttps://github.com/inunosinsi/soycms/blob/master/cms/common/util/CMSPlugin.class.phpをご覧ください。

onEntryOutputの拡張ポイントでは、引数のargsに記事ID(entryId)やcreateAddメソッドを持つオブジェクトが格納されています。

createAddやHTMLLabelについてはPHPモジュール内でHTMLLabelを使用するに記載があります。


今回のコードでブロック内でcms:id="hash"が使えるようになりました。


onEntryOutputについて実際のプラグインで確認したい場合はLazyLoadプラグイン(プラグインID:x_lazy_load)がおすすめです。

https://github.com/inunosinsi/soycms/blob/master/cms/common/site_include/plugin/x_lazy_load/x_lazy_load.php


追記

onEntryOutputの拡張ポイントが実行されるタイミングは

https://github.com/inunosinsi/soycms/blob/master/cms/common/site_include/block/_common/BlockEntryListComponent.class.php

https://github.com/inunosinsi/soycms/blob/master/cms/common/site_include/blog/component/EntryListComponent.class.php

等のブロック実行時に読み込まれる記事オブジェクトのcms:id群が記載されているクラス内にある

CMSPlugin::callEventFunc("onEntryOutput", array("entryId" => $id, "SOY2HTMLObject" => $this,"entry" => $entry));

になります。


追記2

記事投稿画面に設置したカスタムフィールドから値を登録してみるで記事投稿時にデータベースに登録した値を出力するcms:idを設ける

function onEntryOutput($args){
	$entry = $args["entry"];
	$htmlObj = $args["SOY2HTMLObject"];
	
	$htmlObj->createAdd("hoge", "HTMLLabel", array(
		"soy2prefix" => "cms",
		"text" => soycms_get_entry_attribute_value((int)$entry-<getId(), "custom_hoge", "string")
	)); 
}

追記3

HTMLLabelに関する詳しい記述はSOY2HTMLのHTMLLabelを詳しく見るにあります。

同じカテゴリーの記事