Last active
August 19, 2016 18:05
-
-
Save Jany-M/40f4e9c4aef781c5b71babe7eeaaa2b1 to your computer and use it in GitHub Desktop.
[WP] Shortcode for a custom Swiper gallery, extract & convert plain text image urls from WordPress post content
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Setup Swiper before deploy | |
// http://idangero.us/swiper | |
// Add Slideshow Shortcode for WordPress | |
function slideshow_custom_shortcode($atts, $content = null ) { | |
extract( shortcode_atts( array( | |
'plain_text_url' => 'no' // in case the urls are plain text urls, write yes in the parameter eg. [slideshow plain_text_url="yes"]plain text urls here[/slideshow] | |
), $atts ) ); | |
// If we only have a bunch of plain text urls (no a or img tags *sigh*) | |
if($plain_text_url != 'no') { | |
global $post; | |
$doc = new DOMDocument; | |
$doc->loadHTML(get_the_content($post->ID)); | |
$post_content = $doc->textContent; | |
// Get only the urls in the slideshow shortcode | |
$start = '[slideshow plain_text_url="yes"]'; | |
$end = '[/slideshow]'; | |
$post_content = ' ' . $post_content; | |
$ini = strpos($post_content, $start); | |
if ($ini == 0) return ''; | |
$ini += strlen($start); | |
$len = strpos($post_content, $end, $ini) - $ini; | |
$substring_full = substr($post_content, $ini, $len); | |
// Get an array of urls | |
$string_array = explode(PHP_EOL, $substring_full); | |
$new_array = array(); | |
foreach ($string_array as $url) { | |
if(strlen($url) > 1) | |
/* This actually only works in some cases; other times, the Swiper gallery removes the bg image for some reason | |
$new_array[] = '<div class="swiper-slide" style="background-image:url('.$url.')"></div>'; */ | |
$new_array[] = '<div class="swiper-slide"><img src="'.$url.'" /></div>'; | |
} | |
// Take over the content | |
$content = implode(PHP_EOL,$new_array); | |
} | |
// Output the code for the gallery | |
return '<div class="swiper-container gallery-top"> | |
<div class="swiper-wrapper"> | |
'.$content.' | |
</div> | |
<div class="swiper-button-next swiper-button-white"></div> | |
<div class="swiper-button-prev swiper-button-white"></div> | |
</div> | |
<div class="swiper-container gallery-thumbs"> | |
<div class="swiper-wrapper"> | |
'.$content.' | |
</div> | |
</div>'; | |
} | |
add_shortcode( 'slideshow', 'slideshow_custom_shortcode' ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment