Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.