Example slider brick for Genesis Theme Toolkit

All of the WordPress sites I build are based on my Generico starter theme, which uses the excellent Genesis Theme Toolkit by Gary Jones. The key principle of the toolkit is modularity, and “Bricks” can be dropped in to add functionality very easily.

The following is a basic slider brick, which I would typically use with an ACF repeater field and the bxSlider jQuery plugin.

<?php
/**
* Slider brick.
*
* @since 1.0.0
*/
namespace Project\Theme;
use Gamajo\ThemeToolkit\Brick;
/**
* Class Slider
* @package Project\Theme
*/
class Slider extends Brick {
public function apply() {
add_action( 'genesis_after_header', [ $this, 'output_slider' ] );
}
public function output_slider() {
if ( ! $this->has_slider() ) {
return;
}
$post_id = get_the_ID();
$slider_field_name = 'project_slider';
$number_of_slides = get_post_meta( $post_id, $slider_field_name, true );
if ( ! $number_of_slides ) {
return;
}
include locate_template( 'views/slider-open.php' );
for ( $i = 0; $i < $number_of_slides; $i ++ ) {
$slide = $this->get_single_slide( $post_id, $slider_field_name, $i );
include locate_template( 'views/slider-single.php' );
}
include locate_template( 'views/slider-close.php' );
wp_add_inline_script(
'project',
'// <![CDATA[
jQuery(\'.slider ul\').bxSlider({
mode: \'fade\',
pager: false,
auto: true,
pause: 5000
});
// ]]>'
);
}
/**
* Get custom fields making up a single slide.
*
* @param int $post_id ID of the post.
* @param string $field Name of slide field.
* @param int $i Slide iteration.
*
* @return array
*/
public function get_single_slide( $post_id, $field, $i ): array {
return [
'background' => wp_get_attachment_image_src( get_post_meta( $post_id, $field . '_' . $i . '_slide_image', true ), 'full' )[0],
'title' => get_post_meta( $post_id, $field . '_' . $i . '_slide_title', true ),
'content' => get_post_meta( $post_id, $field . '_' . $i . '_slide_content', true ),
];
}
/**
* Check if this page has slider.
*
* At the moment this is a simple conditional check for the home page,
* but it could be expanded to check for a post meta field, a page
* template, or something else entirely.
*
* @return bool
*/
public function has_slider(): bool {
return is_front_page();
}
}
view raw Slider.php hosted with ❤ by GitHub

Reader Interactions

Leave a Reply

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