
Если вы реально устали от поисков плагина для загрузки ваших галерей из такого популярного фотохостинга как Flickr, повторяюсь — именно галереи (вставка отдельных фото по умолчанию включена в WP), то добро пожаловать под кат.
Изначально одно из самых главных критерий в выборе плагина была его легкость, но так как не было найдено подходящих вариантов я решил на быструю руку что-нибудь придумать.
Для приготовления
- Замечательная JavaScript библиотека Galleria
- Открытая и общедоступная CDN jsDelivr
- Немного знаний Shortcode API или инструмент GenerateWP
- Надежная связка руки+голова (опционально)
Файл functions.php
Открываем "волшебный" файл
functions.php нашей темы и подключаем скрипты Galleria с CDN jsDelivr:wp_register_script( 'galleria', '//cdn.jsdelivr.net/g/galleria@1.4.2(galleria.min.js+plugins/flickr/galleria.flickr.js)', false, false, false );
Чтобы понимать как это сделать я приведу пример файла
functions.php действующей по умолчанию темы twentyfifteen со строки 220:Пример файла functions.php
/** * Enqueue scripts and styles. * * @since Twenty Fifteen 1.0 */ function twentyfifteen_scripts() { // Add custom fonts, used in the main stylesheet. wp_enqueue_style( 'twentyfifteen-fonts', twentyfifteen_fonts_url(), array(), null ); // Add Genericons, used in the main stylesheet. wp_enqueue_style( 'genericons', get_template_directory_uri() . '/genericons/genericons.css', array(), '3.2' ); // Load our main stylesheet. wp_enqueue_style( 'twentyfifteen-style', get_stylesheet_uri() ); // Load the Internet Explorer specific stylesheet. wp_enqueue_style( 'twentyfifteen-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentyfifteen-style' ), '20141010' ); wp_style_add_data( 'twentyfifteen-ie', 'conditional', 'lt IE 9' ); // Load the Internet Explorer 7 specific stylesheet. wp_enqueue_style( 'twentyfifteen-ie7', get_template_directory_uri() . '/css/ie7.css', array( 'twentyfifteen-style' ), '20141010' ); wp_style_add_data( 'twentyfifteen-ie7', 'conditional', 'lt IE 8' ); wp_enqueue_script( 'twentyfifteen-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20141010', true ); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } if ( is_singular() && wp_attachment_is_image() ) { wp_enqueue_script( 'twentyfifteen-keyboard-image-navigation', get_template_directory_uri() . '/js/keyboard-image-navigation.js', array( 'jquery' ), '20141010' ); } wp_enqueue_script( 'twentyfifteen-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '20150330', true ); wp_localize_script( 'twentyfifteen-script', 'screenReaderText', array( 'expand' => '<span class="screen-reader-text">' . __( 'expand child menu', 'twentyfifteen' ) . '</span>', 'collapse' => '<span class="screen-reader-text">' . __( 'collapse child menu', 'twentyfifteen' ) . '</span>', ) ); wp_register_script( 'galleria', '//cdn.jsdelivr.net/g/galleria@1.4.2(galleria.min.js+plugins/flickr/galleria.flickr.js)', false, false, false ); // эта сточка кода подключает Galleria } add_action( 'wp_enqueue_scripts', 'twentyfifteen_scripts' );
Если вы хотите, чтобы скрипты подключались только по вызову шорткода, то добавляете условие:
// Add Shortcode scripts function custom_shortcode_scripts() { global $post; if( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'flickr') ) { wp_enqueue_script( 'galleria' ); } } add_action( 'wp_enqueue_scripts', 'custom_shortcode_scripts');
Далее вставляем в конец файла сам Shortcode, который я сгенерировал с помощью инструмента Shortcodes Generator сервиса GenerateWP:
Shortcode
// Add Shortcode function flickr_gallery_shortcode( $atts ) { // Attributes extract( shortcode_atts( array( 'set' => '', ), $atts ) ); // Code return '<div style="position: relative; padding-bottom: 71%; height: 0; overflow: hidden;"> <div id="galleria"></div> </div> <script> var speed = 5000; var clickNext = true; Galleria.loadTheme("//cdn.jsdelivr.net/galleria/1.4.2/themes/classic/galleria.classic.js"); Galleria.on("image", function(e) { var img = e.imageTarget; var picSource = $(img).attr("src"); if (picSource == undefined) { picSource = $("img:first").attr("src"); } var slashPieces = picSource.split("/"); var lastSlash = (slashPieces[slashPieces.length - 1]); var lastPieces = lastSlash.split("_"); }); Galleria.run("#galleria", { responsive: true, preload: 4, initialTransition: "fade", debug: true, idleMode: false, pauseOnInteraction: true, fullscreenDoubleTap: true, backlink: false, transition: "fadeslide", showInfo: true, showCounter: true, clicknext: clickNext, thumbnails: true, flickr: "set:' . $set . '", height: 0.7, flickrOptions: { description: true, max: 100, imageSize: "big", sort: "interestingness-desc", thumbSize: "thumb", }, extend: function() { var gallery = this; this.$("image-nav-right").click(function() { if (speed) { if (!gallery.isPlaying() && !clickNext) { gallery.play(); } else if (clickNext) { if (!gallery.isPlaying()) { gallery.play(); } } } }); this.$("thumb-nav-left, thumb-nav-right").click(function() { if (gallery.isPlaying()) { gallery.pause(); } }); $("#flick").click(function() { gallery.pause(); }); } }); $(document).ready(function() { var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false); var layout = "responsive"; }); </script>'; } add_shortcode( 'flickr', 'flickr_gallery_shortcode' );
И наконец сам шорткод:
[flickr set="id_вашей_галереи"]
Возможные проблемы
Единственная проблема с которой я столкнулся это jQuery.noConflict(). Оказывается по умолчанию в Wordpress библиотека jQuery идет с функцией jQuery.noConflict(), то есть к конце файла jquery.js (wp-includes/js/jquery/jquery.js) добавлена строчка jQuery.noConflict(); которую можно или удалить, — что будет не совсем правильно, или же переподключить jQuery из CDN с помощью кода:
wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', '//cdn.jsdelivr.net/jquery/1.11.3/jquery.min.js', false, '1.11.3', false ); wp_enqueue_script( 'jquery' ); wp_deregister_script( 'jquery-migrate' ); wp_register_script( 'jquery-migrate', '//cdn.jsdelivr.net/jquery.migrate/1.2.1/jquery-migrate.min.js', array( 'jquery' ), '1.2.1', false ); wp_enqueue_script( 'jquery-migrate' );
Плюсы
Самый, на мой взгляд, решающий фактор в данном решении — это легкость. Не нужно писать тысячи строк кода, когда можно обойтись всего несколькими. Более тонкие настройки вы можете найти в официальной документации Galleria.
Минусы
Вы не сможете внедрить в галерею мкроразметку http://schema.org/ImageGallery.
Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.
Считаете ли вы полезным данное решение ?
63.89%Полезное23
25%Бесполезное9
19.44%Я доработаю7
Проголосовали 36 пользователей. Воздержались 18 пользователей.
