Integrate a jQuery plugin to a Wordpress theme

Asked

Viewed 2,370 times

2

I’m using the Nivo Slider on my site from the basic example offered by the plugin. No file header.php of Theme I put the scripts and the <div> with the images pointing to a directory of Theme. And in the footer.php the slider startup.

But how can I make this plugin integration jQuery following the Wordpress standards and pass information dynamically? In the case of slider, images.

header.php

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type='text/javascript' src='<?php echo get_template_directory_uri(); ?>/nivo/jquery.nivo.slider.pack.js'></script>
<link rel='stylesheet' href='<?php echo get_template_directory_uri(); ?>/nivo/nivo-slider.css' type='text/css' media='all' />
<!-- mais código -->    
</head>    
<body <?php body_class(); ?>>
<div id="slider" class="nivoSlider">
    <img src="<?php echo get_template_directory_uri(); ?>/nivo/nemo.jpg" alt="" />
    <a href="http://example.com"><img src="<?php echo get_template_directory_uri(); ?>/nivo/toystory.jpg" alt="" title="#htmlcaption" /></a>
    <img src="<?php echo get_template_directory_uri(); ?>/nivo/up.jpg" alt="" title="This is an example of a caption" />
    <img src="<?php echo get_template_directory_uri(); ?>/nivo/walle.jpg" alt="" />
</div>

footer.php

<script type="text/javascript">
    jQuery(window).load(function() {
        // nivoslider init
        jQuery('#slider').nivoSlider({
            effect: 'boxRainReverse',
            slices:15,
            boxCols:8,
            boxRows:8,
            animSpeed:500,
            pauseTime:5000,
            directionNav:false,
            directionNavHide:false,
            controlNav:true,
            captionOpacity:1
        });
    });
</script>

Q&A-inspired question and answers jQuery(...). nivoSlider is not a Function in Wordpress.

2 answers

6


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 clean and ready to roll.

  • File structure plugin. Files marked in gray come from the Nivo Slider plugin itself.
    inserir a descrição da imagem aqui

  • 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
    });
});
  • 1

    and +1 for showing the most professional way in addition to the link to the plugin base, vlw!

1

The answer of Brasofilo for sure is the most professional way to do this, to only integrate nivoslider in the theme, you must upload the files through wp functions.

In Function.php insert the following.

add_action( 'wp_enqueue_scripts', 'os_meus_scripts' );

function os_meus_scripts() {
    wp_register_script( 'jquery.nivo.slider.pack', get_template_directory_uri() . '/js/nivo/jquery.nivo.slider.pack.js', true );
    wp_register_script( 'nivo-js', get_template_directory_uri() . '/js/nivo/nivo.js', true ); // esse é o arquivo com a chamada.

    wp_enqueue_script('jquery'); // carrega o jquery nativo do wp
    wp_enqueue_script('jquery.nivo.slider.pack');
    wp_enqueue_script('nivo-js');

    // carrega o css do nivo
    wp_register_style( 'nivo-css', get_template_directory_uri() . '/css/nivo/nivo-slider.css');

    wp_enqueue_style( 'nivo-css' );
}

Note that this is the way you should load any script or style into your theme. We also use:

wp_enqueue_script('jquery');

to load the native wordpress jquery and thus avoid conflict.

Within js/Nivo/Nivo-js.js goes the following content.

$(function(){ // chamada short-hand para o ready();
    var options = {
        effect: 'boxRainReverse',
        slices:15,
        boxCols:8,
        boxRows:8,
        animSpeed:500,
        pauseTime:5000,
        directionNav:false,
        directionNavHide:false,
        controlNav:true,
        captionOpacity:1
    };

    $('#slider').nivoSlider(options);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.