Create An Image Slide Plugin Part 8: Create A WordPress Slider Shortcode

Create An Image Slide Plugin Part 8: Create A WordPress Slider Shortcode

In the eighth installment from this series we’ll be creating a shortcode to display multiple slides into a slider.

In the previous post we added the first shortcode for displaying a single slide. Now, we’ll grab multiple of those slides and show them anywhere we want into an animated slider.

If you want to follow along I’ve set up a GitHub repository where you’ll find the code from this series. The finished code for this post is in the part_8 branch. If you want to follow along please download the part_7 branch.

The second shortcode will be called mnsp_slider and we’ll start creating it by updating the class-monospace-slides-shortcodes.php file in the /includes folder.

So open the above mentionaed folder, look for the register_slider_shortcode() method and replace the existing code with the code below:

/**
 * Create and register the 'mnsp_slider' shortcode for displaying multiple slides in a slider.
 *
 * @since 1.0.0
 */
public function register_slider_shortcode() {

	/**
	 * Handler function for the 'mnsp_slider' shortcode.
	 *
	 * @since 1.0.0
	 * @param array $atts    Shortcode attributes.
	 */
	function slider_shortcode( $atts ) {

		$args = shortcode_atts(
			array(
				'id' => '',
			),
			$atts
		);

		$id = (int) $args['id'];

		$transition_type     = esc_attr( get_term_meta( $id, 'mnsp-slider-transition-type', true ) );
		$transition_duration = esc_attr( get_term_meta( $id, 'mnsp-slider-transition-duration', true ) );
		$timeout             = esc_attr( get_term_meta( $id, 'mnsp-slider-timeout', true ) );

		$show_nav = esc_attr( get_term_meta( $id, 'mnsp-slider-show-nav', true ) ) ? 'data-mnsp-slider-show-nav' : '';

		$pause_hover = esc_attr( get_term_meta( $id, 'mnsp-slider-pause-hover', true ) ) ? 'data-mnsp-slider-pause-hover' : '';

		$autoplay = esc_attr( get_term_meta( $id, 'mnsp-slider-autoplay', true ) ) ? 'data-mnsp-slider-autoplay' : '';

		$ratio = esc_attr( get_term_meta( $id, 'mnsp-slider-aspect', true ) );

		$args = array(
			'post_type' => 'mnsp_slide',
			'tax_query' => array( // WPCS: slow query ok.
				array(
					'taxonomy'         => 'mnsp_slider',
					'field'            => 'term_id',
					'terms'            => $id,
					'include_children' => false,
				),
			),
		);

		$slides = get_posts( $args );

		if ( ! empty( $slides ) ) :

			$slider = '<div 
				id="mnsp-slider-' . $id . '" 
				data-mnsp-slider-transition-type="' . $transition_type . '" 
				data-mnsp-slider-transition-duration="' . $transition_duration . '"
				data-mnsp-slider-timeout="' . $timeout . '"
				data-mnsp-slider-ratio="' . $ratio . '"
				' . $show_nav . '
				' . $pause_hover . '
				' . $autoplay . '
				class="mnsp-slider">';

			if ( ! empty( $show_nav ) ) {
				$slider .= '<div class="mnsp-slider-controls" data-glide-el="controls">';
				$slider .= '<button data-glide-dir="<">‹</button>';
				$slider .= '<button data-glide-dir=">">›</button>';
				$slider .= '</div>';
			}

			$slider .= '<div class="glide__track" data-glide-el="track">';

			$slider .= '<div class="glide__slides">';

			foreach ( $slides as $slide_post ) {

				$slide_id = $slide_post->ID;

				$title       = esc_html( get_post_meta( $slide_id, 'mnsp-slide-title', true ) );
				$title_color = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-title-color', true ) );

				$subtitle       = esc_html( get_post_meta( $slide_id, 'mnsp-slide-subtitle', true ) );
				$subtitle_color = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-subtitle-color', true ) );

				$desc       = esc_textarea( get_post_meta( $slide_id, 'mnsp-slide-desc', true ) );
				$desc_color = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-desc-color', true ) );

				$cta_text           = esc_html( get_post_meta( $slide_id, 'mnsp-slide-cta-text', true ) );
				$cta_text_color     = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-cta-text-color', true ) );
				$cta_bg_color       = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-cta-bg-color', true ) );
				$cta_hover_bg_color = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-cta-hover-bg-color', true ) );
				$cta_url            = esc_url( get_post_meta( $slide_id, 'mnsp-slide-cta-url', true ) );
				$cta_target         = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-cta-target', true ) ) ? '_blank' : '_self';

				$image = esc_url( get_post_meta( $slide_id, 'mnsp-slide-image', true ) );

				$horiz_align = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-horiz-align', true ) );

				// We're using the ratio from the slider taxonomy term meta.
				// The ratio of each individual slide is not necessary.
				/* $slide_ratio = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-ratio', true ) ); */ // phpcs:ignore

				$feat_img_opacity = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-featured-opacity', true ) );

				$bg_color = esc_attr( get_post_meta( $slide_id, 'mnsp-slide-bg-color', true ) );

				$has_thumbnail = has_post_thumbnail( $slide_id ) ? ' mnsp-slide-has-thumbnail' : '';

				$slide = '<div 
					id="mnsp-slide-' . $slide_id . '" 
					class="glide__slide mnsp-slide' . $has_thumbnail . '" 
					data-mnsp-slide-title-color="' . $title_color . '" 
					data-mnsp-slide-subtitle-color="' . $subtitle_color . '" 
					data-mnsp-slide-cta-text-color="' . $cta_text_color . '" 
					data-mnsp-slide-cta-bg-color="' . $cta_bg_color . '" 
					data-mnsp-slide-cta-hover-bg-color="' . $cta_hover_bg_color . '" 
					data-mnsp-slide-horiz-align="' . $horiz_align . '" 
					data-mnsp-slide-ratio="' . $ratio . '" 
					data-mnsp-slide-featured-opacity="' . $feat_img_opacity . '" 
					data-mnsp-slide-bg-color="' . $bg_color . '">';

				$slide .= '<div class="mnsp-slide-caption">';

				if ( ! empty( $image ) ) {
					$slide .= '<img class="mnsp-slide-image" src="' . $image . '" />';
				}

				if ( ! empty( $title ) ) {
					$slide .= '<p class="mnsp-slide-title">' . $title . '</p>';
				}

				if ( ! empty( $subtitle ) ) {
					$slide .= '<p class="mnsp-slide-subtitle">' . $subtitle . '</p>';
				}

				if ( ! empty( $desc ) ) {
					$slide .= '<p class="mnsp-slide-desc">' . $desc . '</p>';
				}

				if ( ! empty( $cta_text ) && ! empty( $cta_url ) ) {
					$slide .= '<a class="mnsp-slide-cta" href="' . $cta_url . '" target"' . $cta_target . '">' . $cta_text . '</a>';
				}

				$slide .= '</div>';

				$slide .= get_the_post_thumbnail( $slide_id, 'mnsp-image-' . $ratio, array( 'class' => 'mnsp-slide-featured' ) );

				$slide .= '</div>';

				$slider .= $slide;

			}

			wp_reset_postdata();

			$slider .= '</div></div></div>';

		else :

			$slider = '<p><strong>' . __( 'This slider does not contain any posts.', 'monospace-slides' ) . '</strong></p>';

		endif;

		return $slider;

	}

	add_shortcode( 'mnsp_slider', 'slider_shortcode' );

}

Let’s run through the code above and see what’s going on.

We start with getting the values of the options for the current slider. Each value is assigned to a variable, for later use.

Then, based on the id of the current slider, we get all the slides that are associated with that specific slider. A slide can be assigned to a particular slider in the Sliders meta box from the Add New Slide screen.

Next, we start building our slider and add each slide we previously got. This is where the code gets similar to the one for building a slide shortcode from the previous post.

By going through each of the slides, we get the values of the options for each slide and add the slide to the slider. We do this for all the slides by using a foreach loop.

On the last line of the method we register the mnsp_slider shortcode so WordPress knows what to do when it encounters it.

Going further, we’ll use some JavaScript to animate the slider, and some CSS to correctly display the slider. For the slider animation and functionality we’ll use the Glide.js JavaScript library.

Let’s go into the /public folder and inside the /public/js and /public/css folders add the files needed for the Glide.js library to work properly. You can those from the project’s github repo.

Next, open the file /public/class-monospace-slides-public.php and add the code below to load the newly created files from above.

Inside the enqueue_styles() method:

if( has_shortcode( $post->post_content, 'mnsp_slider') ) {
	wp_enqueue_style( 'glide', plugin_dir_url( __FILE__ ) . 'css/glide.core.min.css', array(), $this->version, 'all' );
}

Inside the enqueue_script() method:

if( has_shortcode( $post->post_content, 'mnsp_slider') ) {
	wp_enqueue_script( 'glide', plugin_dir_url( __FILE__ ) . 'js/glide.min.js', array(), $this->version, true );
}

You’ll notice that we only load these files if the current page contains out slider shortcode.

Next, open the /public/css/monospace-slides-public.css and replace the contents with the code below in order to correctly display a slider:

.mnsp-slide,
.mnsp-slider {
	position: relative;
	padding: 0 !important;
}

.mnsp-slide {
	display: flex;
	height: auto;
	justify-content: center;
	align-items: center;
	font-size: 1rem;
	overflow: hidden;
}

.mnsp-slider:hover {
	cursor: -webkit-grab;
}

.mnsp-slide::before,
.mnsp-slider::before { /* for the aspect ratio functionality */
	content: "";
	width: 1px;
	margin-left: -1px;
	float: left;
	height: 0;
}

.mnsp-slide::after,
.mnsp-slider::after { /* to clear float */
	content: "";
	display: table;
	clear: both;
}

.mnsp-slide[data-mnsp-slide-horiz-align="left"] .mnsp-slide-caption {
	text-align: left;
}

.mnsp-slide[data-mnsp-slide-horiz-align="center"] .mnsp-slide-caption {
	text-align: center;
}

.mnsp-slide[data-mnsp-slide-horiz-align="right"] .mnsp-slide-caption {
	text-align: right;
}

.mnsp-slide-caption {
	position: relative;
	width: 100%;
	padding: 5vmin;
	z-index: 2000;
}

.mnsp-slide-image {
	max-width: 15%;
}

.mnsp-slide-title {
	font-size: 1.25em;
}

.mnsp-slide-subtitle {
	font-size: 1.1em;
}

.mnsp-slide .mnsp-slide-caption .mnsp-slide-cta,
.mnsp-slide .mnsp-slide-caption .mnsp-slide-cta:hover,
.mnsp-slide .mnsp-slide-caption .mnsp-slide-cta:focus,
.mnsp-slide .mnsp-slide-caption .mnsp-slide-cta:active {
	color: white;
	text-decoration: none;
	border: 0;
	box-shadow: none;
}

.mnsp-slide .mnsp-slide-caption .mnsp-slide-cta {
	display: inline-block;
	font-family: Raleway, "Open Sans", "Source Sans Pro", sans-serif;
	font-size: smaller;
	font-weight: bold;
	text-transform: uppercase;
	line-height: 1;
	padding: 16px 30px;
	background-color: black;
	cursor: pointer;
	transition: all 0.5s ease;
}

.mnsp-slide-caption > * + * {
	margin: 0.75rem 0 0 0;
}

.mnsp-slide-featured {
	position: absolute;
	height: 100%;
	object-fit: cover;
	z-index: 1000;
}

.mnsp-slide[data-mnsp-slide-ratio="wide"]::before,
.mnsp-slider[data-mnsp-slider-ratio="wide"]::before {
	padding-top: 56.25%;
}

.mnsp-slide[data-mnsp-slide-ratio="classic"]::before,
.mnsp-slider[data-mnsp-slider-ratio="classic"]::before {
	padding-top: 75%;
}

.mnsp-slide[data-mnsp-slide-ratio="square"]::before,
.mnsp-slider[data-mnsp-slider-ratio="square"]::before {
	padding-top: 100%;
}

.mnsp-slider-controls {
	position: absolute;
	width: 100%;
	height: 3rem;
	top: 50%;
	transform: translateY(-50%);
	z-index: 3000;
	opacity: 0;
	transition: opacity 0.5s ease;
}

.mnsp-slider:hover .mnsp-slider-controls {
	opacity: 1;
}

.mnsp-slider-controls > * {
	display: inline-block;
	position: absolute;
	width: 3rem;
	height: 3rem;
	color: white;
	font-weight: bold;
	line-height: 1;
	background: rgba(0, 0, 0, 0.25);
	padding: 0;
	border-radius: 50%;
	border: none;
	transition: all 0.5s ease;
}

.mnsp-slider-controls > *:hover {
	background: rgba(0, 0, 0, 0.35);
}

.mnsp-slider-controls > *:first-child {
	left: 2rem;
}

.mnsp-slider-controls > *:last-child {
	right: 2rem;
}

The last step is to actually start the slider by calling the Glide.js code for each slider on the current page. Open the /public/js/monospace-slides.public.js and add the code below just before the end of the file, inside the IIFE function.

sliders.forEach( function( element ) {

	var $this = element,
		slider,
		autoplay = $this.hasAttribute( 'data-mnsp-slider-autoplay' ),
		pauseHover = $this.hasAttribute( 'data-mnsp-slider-pause-hover' ),
		transitionDuration = $this.dataset.mnspSliderTransitionDuration || 1000,
		timeout = 0;

	if ( autoplay ) {
		timeout = $this.dataset.mnspSliderTimeout;
	}

	slider = new Glide( $this, {
		type: 'carousel',
		autoplay: timeout,
		hoverpause: pauseHover,
		animationDuration: transitionDuration,
		perView: 1
	} ); // eslint-disable-line

	slider.mount();

} ); // eslint-disable-line

That’s it! We created another shortcode that collects multiple slides and displays them into an animated sliders with some custom options.

To display a slider, go to the Sliders screen and just copy the content of the Shortcode column, including the square brackets and paste it in any post or page.

Slider Custom WordPress Shortcode Admin Column

At The End

The code in this post was somewhat familiar with the code from the previous post so I hope it was a littler easier to follow.

This was the last post in this series. Now you know how to create a WordPress plugin using custom post types, custom taxonomies and custom meta information.

Please feel free to share your feedback regarding what we’ve been doing so far or any issues you may have.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.