JAVASCRIPTWORDPRESS UTILS
JAVASCRIPT УТИЛИТЫ В ЯДРЕWORDPRESS, КОТОРЫЕ МОГУТ
СДЕЛАТЬ ЖИЗНЬ РАЗРАБОТЧИКАПРОЩЕ.
Докладчик: / Viktor Kuliebiakin [email protected]
var frame;// some magicframe = wp.media({ title: 'Insert Image(s)', multiple: true, library: { type: 'image' }, button: { text: 'Insert into gallery' }});// some magicframe.open();
ПЕРЕД ТЕМ КАК НАЧАТЬ$some_function = function () { // do something};/** * For logged in users */add_action( 'wp_ajax_some_action', $some_function );/** * For not logged in users */add_action( 'wp_ajax_nopriv_some_action', $some_function );
КОЕ-ЧТО ЕЩЕwp_send_json( [ 'success' => false, 'data' => [ 'email' => __( 'Email is invalid.' ) ]] );
wp_send_json_success();
...
wp_send_json_success( [ // some answer] );
...
wp_send_json_error( [ 'email' => __( 'Invalid email address.' )] );
JQUERY ONLYjQuery.ajax('http://site.com/wp-admin/admin-ajax.php', { data: { action: 'some_action', email: '[email protected]', ... }, method: 'POST', success: function (response) {
if (response.success) { // do something with response.data } else { // show error etc. from response.data } }});
WP.AJAXwp.ajax.send('some_action', { data: { email: '[email protected]', ... }, success: function (response) { // do something with response }, error: function (error) { // show error etc. }});
<script type="text/html" id="tmpl-post">
// Your template
</script>
Шаблон оборачивается тегом <script>Тип тега должен быть text/htmlЗначение id должно иметь префикс tmpl-
НЕСКОЛЬКО ПРАВИЛ ПРИ РАБОТЕ СШАБЛОНОМ
Синтаксис похож на Для вывода данных используется {{{ ... }}}Для вывода HTML-безопасных данных {{ ... }}Для вычислений <# ... #>Данные доступны из объекта data
Mustache
<article> <h3>{{{data.title}}}</h3> <# if (data.image) { #> <figure> <img src="{{data.image}}" alt="thumbnail"> </figure> <# } #> {{{data.excerpt}}} <a href="{{data.permalink}}">Read more</a></article>
var tmpl = wp.template('post');
$('.post-list').append(template({ title: 'Hello World!', image: 'path/to/image.jpg', excerpt: '<p>Welcome to WordPress. This is your first post.</p>' permalink: 'https://site.com/2015/05/29/hello-world/'}));
<article> <h3>Hello World!</h3> <figure> <img src="path/to/image.jpg" alt="thumbnail"> </figure> <p>Welcome to WordPress. This is your first post.</p> <a href="https://site.com/2015/05/29/hello-world/">Read more</a></article>
wp.html.string({ tag: 'input', single: true, attrs: { type: 'email', id: 'contact-email-1', name: 'email', 'class': 'input-field', placeholder: 'Your Email' }});
<input type="email" id="contact-email-1" name="email" class="input-field" placeholder="Your Email" />
var button = new wp.shortcode({ tag: 'button', type: 'closed', // closed - default, single, self-closed attrs: { title: 'Click me!', type: 'primary', icon: 'palmtree' }, content: 'Click me!'});
ЕЩЕ ПАРУ ПОЛЕЗНЫХ МЕТОДОВwp.shortcode.next(tag, text, index);
wp.shortcode.replace(tag, text, callback);
someText = wp.shortcode.replace('button', someText, function (shortcode) { return wp.html.string({ tag: 'button', content: shortcode.content, attrs: { 'class': shortcode.get('type') + '-button dashicons-' + shortcode.get('icon'), title: shortcode.get('title') } }); });
some text...<button class="primary-button dashicons-palmtree" title="Click me!">Click me!</button>...some text
ДОБАВЛЯЕМ ДАННЫЕ ДЛЯОТПРАВКИ НА СЕРВЕР
newData = { some: 'data'};data = wp.heartbeat.isQueued('your-key');
if (data) { newData = jQuery.extend(data, newData);}
wp.heartbeat.enqueue( 'your-key', newData, true);
ПОЛУЧАЕМ ЗАПРОС НА СЕРВЕРЕ СПОМОЩЬЮ ЭКШЕНОВ И ФИЛЬТРОВ
heartbeat_received$response, $data, $screen_id
heartbeat_send$response, $screen_id
heartbeat_tick$response, $screen_id
ПОЛУЧАЕМ ОТВЕТ В БРАУЗЕРЕ СПОМОЩЪЮ СОБЫТИЙ
jQuery(document).on('heartbeat-tick', function(event, data) { if (data.hasOwnProperty('your-key')) { // do something with data }});
ЧТО ХОТЕЛОСЬ БЫ СКАЗАТЬ ВКОНЦЕ
Загрузка дополнительных файлов,дополнительные запросыИспользование на больших проектахИспользование в админке