Written by Anonymous
add_action('init', function() {
wp_register_script(
'myplugin-restrict-block-js',
false, // 外部ファイルなし
['wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n'],
null
);
$js = <<<EOF
(function(wp) {
const { registerBlockType } = wp.blocks;
const { createElement: el, Fragment } = wp.element;
const { InnerBlocks, InspectorControls } = wp.blockEditor;
const { PanelBody, TextControl, SelectControl } = wp.components;
registerBlockType('myplugin/restrict', {
title: '制限ブロック',
icon: 'lock',
category: 'cocoon-block',
attributes: {
mode: { type: 'string', default: 'period' },
from: { type: 'string', default: '' },
to: { type: 'string', default: '' },
msg: { type: 'string', default: 'こちらのコンテンツはログインユーザーのみに表示されます。' },
},
edit: function(props) {
const { attributes, setAttributes } = props;
return el(Fragment, null,
el(InspectorControls, null,
el(PanelBody, { title: '制限設定', initialOpen: true },
el(SelectControl, {
label: '制限タイプ',
value: attributes.mode,
options: [
{ label: '期間制限', value: 'period' },
{ label: 'ログイン制限', value: 'login' }
],
onChange: val => setAttributes({ mode: val })
}),
attributes.mode === 'period' && el(Fragment, null,
el(TextControl, {
label: '開始日時',
value: attributes.from,
onChange: val => setAttributes({ from: val }),
placeholder: 'YYYY-MM-DD HH:MM:SS'
}),
el(TextControl, {
label: '終了日時',
value: attributes.to,
onChange: val => setAttributes({ to: val }),
placeholder: 'YYYY-MM-DD HH:MM:SS'
})
),
attributes.mode === 'login' && el(TextControl, {
label: 'ログイン外メッセージ',
value: attributes.msg,
onChange: val => setAttributes({ msg: val })
})
)
),
el('div', {
style: {
border: '2px dashed #ccc',
padding: '15px',
background: '#f9f9f9',
position: 'relative'
}
},
el('span', {
style: {
position: 'absolute',
top: '-12px',
left: '10px',
background: '#fff',
padding: '0 5px',
fontSize: '11px',
color: '#666'
}
}, attributes.mode === 'period' ? '期間制限中' : 'ログイン制限中'),
el(InnerBlocks)
)
);
},
save: function() {
// PHP側で処理するため、中身のコンテンツのみ保存
return el(InnerBlocks.Content);
}
});
})(window.wp);
EOF;
wp_add_inline_script('myplugin-restrict-block-js', $js);
// 3. サーバーサイドでのレンダリング設定(the_contentフィルタの代わり)
register_block_type('myplugin/restrict', [
'editor_script' => 'myplugin-restrict-block-js',
'render_callback' => function($attributes, $content) {
$mode = $attributes['mode'] ?? 'period';
if ($mode === 'period') {
$from = !empty($attributes['from']) ? ' from="' . esc_attr($attributes['from']) . '"' : '';
$to = !empty($attributes['to']) ? ' to="' . esc_attr($attributes['to']) . '"' : '';
return do_shortcode('[campaign' . $from . $to . ']' . $content . '[/campaign]');
} else {
$msg = !empty($attributes['msg']) ? ' msg="' . esc_attr($attributes['msg']) . '"' : '';
return do_shortcode('[login_user_only' . $msg . ']' . $content . '[/login_user_only]');
}
}
]);
});