facebook twitter hatena line email

Cms/wordpress/プラグインショートコード

提供: 初心者エンジニアの簡易メモ
2015年5月20日 (水) 02:59時点における127.0.0.1 (トーク)による版 (ページの作成:「==記事中の[hw]をhelloworldに変更する== <?php /* Plugin Name: helloworld_shortcode Plugin URI: http://example.com/plugin.php Description: 記事中の[hw]...」)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

記事中の[hw]をhelloworldに変更する

<?php
/*
Plugin Name: helloworld_shortcode
Plugin URI: http://example.com/plugin.php
Description: 記事中の[hw]をhelloworldに変更する
Version: 1.0
Author: author1
Author URI: http://example.com/author1
*/
function hello() {
    return 'Hello, World!';
}
add_shortcode('hw', 'hello');
?>

記事中の[hw hoge=test]をhelloworldに変更する(パラメータ付)

<?php
/*
Plugin Name: helloworld_shortcode_param
Description: 記事中の[hw hoge=test]をhelloworldに変更する
*/
function hello($atts) {
    return 'Hello, World!'.$atts['hoge'];
}
add_shortcode('hw', 'hello');
?>

記事中の[hw]hoge[/hw]をhelloworldに変更する(囲い)

<?php
/*
Plugin Name: helloworld_shortcode_kakoi
Description: 記事中の[hw]hoge[/hw]をhelloworldに変更する
*/
function hello($atts, $content = null) {
    return 'Hello, World!'.$content;
}
add_shortcode('hw', 'hello');
?>

ショートコード内で他のショートコードの入れ子を許可する

以下のように戻り$contentをdo_shortcodeで囲うとネストが許可される

function caption_shortcode($atts, $content = null)
{
    return '<span class="caption">' . do_shortcode($content) . '</span>';
}

クラス化

class Plugin_ShortCode1
{
  public function exec($atts, $content = null)
  {
    return 'Hello, World!' . $content;
  }
}
add_shortcode('hw', array('Plugin_ShortCode1', 'exec'));