Как создать пользовательский плагин слайд-шоу wordpress?


Как создать пользовательский плагин слайд-шоу wordpress? Я искал учебные пособия в Google, но не смог их найти, не могли бы вы, ребята, дать здесь учебник или ссылку на некоторые другие учебные пособия по плагинам для слайд-шоу?

 3
Author: Mouse Hello, 2012-03-24

2 answers

Итак... это моя реализация слайд-шоу:

Этот код я использую для создания слайд-шоу на основе плагина flexslider jQuery (Спасибо, Дэвид!). Это также дает пользователю флажок, чтобы он мог выбрать, какие изображения включить в слайд-шоу, а какие пропустить. Изображения взяты из вложений в пост, если вам нужно общее слайд-шоу, не связанное с каким-либо постом, вам нужно реализовать решение, которое дал Дэвид:)

Это функция/фильтр, который я использую для добавления установите флажок внутри загрузчика мультимедиа, чтобы клиент мог выбрать, хочет ли он включить изображение в слайд-шоу или нет.

    //      Adding a custom checkbox to the Media Uploader
function monster_image_attachment_slideshow($form_fields, $post) {
    $foo = (bool)get_post_meta($post->ID, "rt-image-link", true);

    $form_fields["rt-image-link"] = array(
        "label" => __("Include in gallery?"),
        'input' => 'html',
        'html' => '<label for="attachments-'.$post->ID.'-foo"> ' . '<input type="checkbox" id="attachments-'.$post->ID.'-foo" name="attachments['.$post->ID.'][rt-image-link]" value="1"'.($foo == true ? ' checked="checked"' : '').' /> Yes</label>  ',
        "value" => $foo,
        "helps" => __("Check this if you want to include this image in your gallery"),
    );
   return $form_fields;
}
// now attach our function to the hook
add_filter("attachment_fields_to_edit", "monster_image_attachment_slideshow", null, 2);

// Saving the media field
function monster_image_attachment_slideshow_to_save($post, $attachment) {
    // $attachment part of the form $_POST ($_POST[attachments][postID])

        update_post_meta($post['ID'], 'rt-image-link', $attachment['rt-image-link']);

    return $post;
}
// now attach our function to the hook.
add_filter("attachment_fields_to_save", "monster_image_attachment_slideshow_to_save", null , 2);

Затем я использую эту функцию также в своем файле функций (оба они могут быть включены в плагин, если вы этого хотите):

    //      This is the funcion that rolls out my slideshow html
function m_slideshow_outputter( $post_id ,$size = 'large', $thumbnail_size = '') {
    global $post;
    $got_slides = false;

    $args = array(
        'post_type' => 'attachment',
        'numberposts' => -1,
        'post_status' => null,
        'post_parent' => $post_id,
        'order' => 'ASC', 
        'orderby' => 'menu_order'
    );

    //      Getting attachmentes (images)
    $attachments = get_posts( $args );

    if ( $attachments ) {
        $cm_output = '<div class="flex-container"><div class="flexslider"><ul class="slides">';

        //  looping through each attachment for the given post
        foreach ( $attachments as $attachment ) {
            $image_attributes = wp_get_attachment_image_src( $attachment->ID, $size  );


            $cm_src = $image_attributes[0];
            $cm_width = $image_attributes[1];
            $cm_height = $image_attributes[2];

            //  This part gets custom metainformation about the attachement. 
            //  I have made a custom checkbox inside the media uploader. If the checkbox is checked the image is included. See the checkbox code above :) 
            $gallery_check_array = get_post_meta($attachment->ID, "rt-image-link");
            $gallery_check = $gallery_check_array[0];

            //  So just include the picture if the checkbox in checked :)
            if ( $gallery_check == 1) {
                $got_slides = true;
                $cm_output .= '<li><img class="picture-'.$post_id.'-'.$attachment->ID .'" src="'.$cm_src.'" alt="Slideshow" width="'.$cm_width.'" height="'.$cm_height.'"/></li>';
            }
        }

        $cm_output .= '</ul></div></div><!-- End flexslider -->';
        //  Outputting the thumbnails if a thumbnail size has been entered. Ignore this or delete this part if you dont need thumbnails
        if ($thumbnail_size) {
            $cm_output .= '<div class="slideshow-thumbails"><ul>';

            foreach ( $attachments as $attachment ) {
                $thumbnail_attributes = wp_get_attachment_image_src( $attachment->ID, $thumbnail_size  );


                $cm_tumb_src = $thumbnail_attributes[0];
                $cm_tumb_width = $thumbnail_attributes[1];
                $cm_tumb_height = $thumbnail_attributes[2];

                                $thumbnail_check_array = get_post_meta($attachment->ID, "rt-image-link");
            $thumbnail_check = $thumbnail_check_array[0];

            // doing the same check as above for each thumbnail.
            if ( $thumbnail_check == 1) {
                    $cm_output .= '<li><img class="picture-'.$post_id.'-'.$attachment->ID .'" src="'.$cm_tumb_src.'" alt="Slideshow" width="'.$cm_tumb_width.'" height="'.$cm_tumb_height.'" /></li>';
                }
            }
            $cm_output .= '</ul></div>';
        }
        //If there are images in the slidehow return them, else return nothing.
        if ($got_slides) {
            return($cm_output);
        } else {
            return("");
        }
    // if the post has no images return nothing.
    } else {
        return("");
    }   
}

Затем вам нужно включить jquery:

    //      How to add custom js to Front end
add_action('wp_print_scripts', 'monster_front_js');
function monster_front_js(){    
    wp_register_script('flexslider', get_template_directory_uri() . '/js/jquery.flexslider-min.js', array('jquery'), '1.0' );
    wp_register_script('monster_front', get_template_directory_uri() . '/js/monster_front.js', array('jquery', 'flexslider'), '1.0' );
    wp_enqueue_script('monster_front');
    wp_enqueue_script('jquery.flexslider-min.js');
}

Это находится внутри пользовательского jquery, настраивающего слайд-шоу:

      jQuery(window).load(function() {
    jQuery('.flexslider').flexslider({
        controlsContainer: ".flex-container", 
        controlNav: false, 
        directionNav: true
    });
  });

И css, связанный со слайд-шоу:

add_action('wp_print_styles', 'monster_front_styles');
function monster_front_styles() {
    wp_register_style( 'flexslider_style', get_template_directory_uri() . '/css/flexslider.css');
    wp_enqueue_style('flexslider_style');
}

И Наконец! Код слайд-шоу, готовый для вставки в ваш интерфейс темы.:)

<?php echo m_slideshow_outputter( $post->ID ,'large', 'thumbnail'); ?><!-- This is the slideshow :) -->

Единственным обязательным параметром является идентификатор записи. Второй параметр по умолчанию имеет значение "большой", но вы можете выбрать, какой размер изображения возвращать. Последний параметр задает размер миниатюры изображения, если этот параметр оставить пустым, миниатюры не будут возвращены.

Надеюсь, это не перебор. :)

 2
Author: Ole Henrik Skogstrøm, 2012-03-25 13:09:58

Поскольку ваш вопрос немного завышен, здесь представлена простая реализация WP_Query, простой для установки слайдера Javascript и Для размещения миниатюр.

Добавьте этот фрагмент кода на свою страницу, которую вы хотели бы видеть своим слайдером

function blogSlider() {

// The Query 
$the_query = new WP_Query( 'posts_per_page=5' );

// The Loop 
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
  <li>
    <?php if ( has_post_thumbnail() ) { the_post_thumbnail( 'large-thumb' ); } ?>
    <div class="flex-caption">
      <h3 class="larger"><?php the_title(); ?></h3>

      <?php the_excerpt(); ?> // This is really dealers choice, however for this purpose it should show you a good example of how the data is being iterated through.

    </div>
  </li>
<?php endwhile;

// Reset Post Data
wp_reset_postdata();
}

Добавьте их в свой functions.php :

//Enqueue Slider Script
wp_enqueue_script( 'slider', get_template_directory_uri() . '/xxx/jquery.flexslider-min.js', 'jquery' );
//Enqueue Slider Style
wp_enqueue_style( 'slider', get_template_directory_uri() . '/xxx/flexslider.css' );

А также:

//Add the Thumbnail Image size 
if ( function_exists( 'add_image_size' ) ) { 
  add_image_size( 'large-thumb', 960, 276, true );
}

Вам нужно обязательно загрузить и извлечь Flexslider или любой другой скрипт слайдера, который вы предпочитаете.

Как только вы извлекли Flexslider, вы поместите этот фрагмент в свой заголовок/страницу с помощью слайдера/Yepnope:

//Scripts to place
 <script type="text/javascript">
   jQuery(window).load(function() {
    jQuery('.flexslider').flexslider({
      controlsContainer: "#none",
    });
 </script>

Как только вы будете готовы вывести свой слайдер, вставьте этот код туда, где вы хотите, чтобы ваш слайдер выводился:

<div class="flexslider">
  <ul class="slides">
    <?php blogSlider(); ?>
  </ul>
 </div>

Удачи, я надеюсь, что это приведет вас на достаточно хороший путь:)

Вот фрагмент для добавления пользовательского типа записи, который функция может выполнять в цикле

//Generic CPT Snippet 
function 46685_slider_type() {
    register_post_type( 'slider',
        array(
            'labels' => array(
                'name' => __( 'Featured Images' ),
                'singular_name' => __( 'Featured Image' ),
                'add_new' => __( 'Add Another Featured Image' ),
                'add_new_item' => __( 'Add New' ),
                'edit_item' => __( 'Edit Featured Image' ),
                'new_item' => __( 'New Featured Image' ),
                'view_item' => __( 'View Featured Image' ),
                'search_items' => __( 'Search Featured Image' ),
                'not_found' => __( 'No Featured Image found' ),
                'not_found_in_trash' => __( 'No Featured Images found in trash' )
            ),
            'public' => true,
            'supports' => array( 'title', 'editor', 'thumbnail' ),
            'capability_type' => 'page',
            'rewrite' => array("slug" => "slider"), // Permalinks format
            'menu_position' => 9 // int
        )
    );
}
//Add CPT to System some systems may require a rewrite flush.
add_action( 'init', '46685_slider_type' );

Вам также нужно будет изменить свой $the_query на:

$the_query = new WP_Query( array('posts_per_page' => '5', 'post_type' => 'slider') );
 2
Author: David, 2012-03-25 00:00:50