The first observation is that it is more appropriate to create a plugin and make this functionality regardless of theme, thus, when changing theme, it is much easier to make the migration of Slider.
The second is that we should only use other versions of jQuery (instead of the one that comes embedded in Wordpress) if we know what we’re doing. This avoids conflicts with other plugins and themes.
The carelessness when using jQuery correctly in WP is responsible for numerous problems and bugs.
The plugin that follows is adapting the question code, noting the following:
As always, the starting point is the code of Plugin Base Demo (moderator @toscho on Wordpress Developers). Is a basis Oop clean and ready to roll.
File structure plugin. Files marked in gray come from the Nivo Slider plugin itself.
Main functions wordpress plugins_url
, wp_enqueue_script
, wp_register_script
, wp_enqueue_scripts
, get_children
and wp_get_attachment_image_src
.
Check the use of scripts as dependencies. Our custom archive (nivo-start
) is loaded using as dependencies a registered file (nivo-pack
) and jQuery embedded in WP.
Check the use of $
as a shortcut to jQuery
in the archive start-nivo.js
.
The Slider is used as Shortcode, pointing to a specific post or page. Here, for example, just after the <body>
in the archive header.php
of Theme active:
<?php echo do_shortcode('[teste-nivo id="105"]'); ?>
To organize the slides you can use a Custom Post Type, where each post would contain an image gallery to make sliders; or a Posts category; or a Page master with several daughters. Upload the images, Caption and Description correspond to post_excerpt
and post_content
of the attached file.
The private method get_nivo_page($id)
renders HTML from the $id
passed by Shortcode.
The private method get_nivo_default()
does the output of string
HTML inside the Shortcode is built using the heredoc syntax of PHP. Attention to the lock identifier: the HTML;
final must not have none blank space before the identifier.
Filing cabinet meu-nivo-slider.php
:
<?php
/**
* Plugin Name: (SOPT) Nivo Slider
* Plugin URI: /a/9546/201
* Description: Adaptação do exemplo básico do Nivo Slider como plugin de WordPress
* Author: brasofilo
* License: GPLv3
*/
add_action(
'plugins_loaded',
array ( B5F_Nivo_Slider::get_instance(), 'plugin_setup' )
);
class B5F_Nivo_Slider
{
protected static $instance = NULL;
public $plugin_url = '';
public $plugin_path = '';
/**
* Acessar a instancia de trabalho deste plugin.
*
* @wp-hook plugins_loaded
* @return object of this class
*/
public static function get_instance()
{
NULL === self::$instance and self::$instance = new self;
return self::$instance;
}
/**
* Usado para iniciar os trabalhos normais do plugin.
*
* @wp-hook plugins_loaded
* @return void
*/
public function plugin_setup()
{
$this->plugin_url = plugins_url( '/', __FILE__ );
$this->plugin_path = plugin_dir_path( __FILE__ );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
add_shortcode( 'teste-nivo', array( $this, 'shortcode' ) );
}
/**
* Constructor. Deixado publico e vazio intencionalmente.
*
* @see plugin_setup()
*/
public function __construct() {}
/**
* Carregar scripts e styles
*
* @wp-hook wp_enqueue_scripts
*/
public function enqueue ()
{
wp_register_script(
'nivo-pack',
$this->plugin_url . 'js/jquery.nivo.slider.pack.js'
);
wp_enqueue_script( 'nivo-start', $this->plugin_url . 'js/start-nivo.js', array( 'jquery', 'nivo-pack' ), false, true );
wp_enqueue_style( 'nivo-css', $this->plugin_url . 'css/nivo-slider.css' );
}
/**
* Criar HTML para o Shortcode
*
* @wp-hook add_shortcode
*/
public function shortcode( $atts )
{
// Shortcode definiu uma ID de post, eg, [teste-nivo id="NUMERO"]
if( isset( $atts['id'] ) )
$output = $this->get_nivo_page( $atts['id'] );
// ID não fornecido, usar template do demo
else
$output = $this->get_nivo_default();
return $output;
}
/**
* Prepara o HTML puxando os attachments do post com $id
*
* @return string
*/
private function get_nivo_page( $id )
{
$attachments = get_children( array(
'post_parent' => $id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image'
));
if( $attachments )
{
$output = '<div id="slider" class="nivoSlider">';
foreach( $attachments as $attach )
{
$image = wp_get_attachment_image_src( $attach->ID, 'full' );
$output .= sprintf(
'%s<img src="%s" alt="" title="%s" />%s',
empty( $attach->post_content ) ? '' : "<a href='$attach->post_content'>",
$image[0],
empty( $attach->post_excerpt ) ? '' : $attach->post_excerpt,
empty( $attach->post_content ) ? '' : '</a>'
);
}
$output .= '</div>';
}
else
$output = '<h2>Faça upload de imagens no post/página!</h2>';
return $output;
}
/**
* Prepara o HTML usando o código demonstrativo do Nivo
*
* @return string
*/
private function get_nivo_default()
{
$nivo_folder = $this->plugin_url . 'img';
$output = <<<HTML
<div id="slider" class="nivoSlider">
<img src="$nivo_folder/nemo.jpg" alt="" />
<a href="http://example.com"><img src="$nivo_folder/toystory.jpg" alt="" title="#htmlcaption" /></a>
<img src="$nivo_folder/up.jpg" alt="" title="This is an example of a caption" />
<img src="$nivo_folder/walle.jpg" alt="" />
</div>
<div id="htmlcaption" class="nivo-html-caption">
<strong>This</strong> is an example of a <em>HTML</em> caption with <a href="#">a link</a>.
</div>
HTML;
return $output;
}
}
Filing cabinet start-nivo.js
:
jQuery( document ).ready( function( $ ) // $ como atalho de jQuery
{
$('#slider').nivoSlider({
effect: 'random',
slices: 15,
boxCols: 8,
boxRows: 4,
animSpeed: 500,
pauseTime: 3000,
startSlide: 0,
directionNav: true,
controlNav: true,
controlNavThumbs: false,
pauseOnHover: true,
manualAdvance: false,
prevText: 'Anterior',
nextText: 'Seguinte',
randomStart: false
});
});
and +1 for showing the most professional way in addition to the link to the plugin base, vlw!
– igrossiter