1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
<?php
namespace SIW\Admin;
class Shortcodes {
public static function init() {
$self = new self();
add_action( 'admin_init', [ $self, 'add_shortcode_button' ] );
add_action( 'admin_enqueue_scripts', [ $self, 'localize_script' ] );
}
public function add_shortcode_button() {
if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
return;
}
if ( get_user_option( 'rich_editing' ) !== 'true' ) {
return;
}
add_filter( 'mce_external_plugins', [ $this, 'add_tinymce_plugin' ] );
add_filter( 'mce_buttons', [ $this, 'register_button' ] );
}
public function localize_script() {
$shortcodes = siw_get_data( 'shortcodes' );
array_walk( $shortcodes, [ $this, 'format_shortcode' ] );
$siw_shortcodes = [
'title' => __( 'SIW Shortcodes', 'siw' ),
'shortcodes' => $shortcodes,
];
wp_localize_script( 'editor', 'siw_shortcodes', $siw_shortcodes );
}
protected function format_shortcode( &$value ) {
$properties = ['shortcode', 'title', 'attributes'];
$value = array_intersect_key( $value, array_flip( $properties ) );
if ( isset( $value['attributes'] ) ) {
$value['attributes'] = array_map( [ $this, 'format_attribute'], $value['attributes'] );
}
}
protected function format_attribute( array $data ) {
switch ( $data['type'] ) {
case 'text':
$attribute = [
'type' => 'textbox',
'name' => $data['attr'],
'label' => $data['title'],
];
break;
case 'select':
$attribute = [
'type' => 'listbox',
'name' => $data['attr'],
'label' => $data['title'],
'values' => array_map( [ $this, 'format_options'], array_keys( $data['options'] ), $data['options'] ),
];
break;
default:
}
return $attribute;
}
protected function format_options( string $value, string $label ) {
return [
'value' => $value,
'text' => $label,
];
}
public function add_tinymce_plugin( array $plugins ) {
$plugins['siw_shortcodes'] = SIW_ASSETS_URL . 'js/admin/siw-shortcodes.js';
return $plugins;
}
public function register_button( array $buttons ) {
array_push( $buttons, 'siw_shortcodes' );
return $buttons;
}
}