QUẢNG CÁO: Nếu các bạn có nhu cẩu về THEME - PLUGIN được làm theo nhu cầu riêng của bạn với giá rẻ hãy truy cập vào https://wpdev.io.vn

Tạo Slide Ảnh Slick Carousel Cho WordPress Không Dùng Plugin

Mới đây, ACF một plugin dùng để custom giao diện nổi tiếng đã bị WordPress khai tử. Nếu bạn tìm kiếm phương pháp để thay thế ACF để tạo một custom field để tạo slide ảnh cho bài viết thì có nhiều plugin, nhưng trong bài viết này, mình sẽ chia sẻ với bạn cách không dùng plugin và kết hợp với thư viện của Slick.

Slick Carousel là gì?

Slick Carousel là một thự viện javascript được dùng rất phổ biến bên cạnh Owl Carousel, để tạo carousel một cách hiệu quả và dễ dàng. Nó hỗ trợ khá đầy đủ tình năng cần thiết cho carousel như sau:

  • Fully responsive. Scales với container .
  • Separate settings cho từng breakpoint
  • Swipe enabled / disabled
  • Desktop mouse dragging
  • Infinite looping.
  • Hỗ trợ arrow key navigation
  • Thêm, xoá, lọc các slides
  • Autoplay, dots, arrows, callbacks, etc…
Tạo Slide Ảnh Slick Carousel Cho WordPress Không Dùng Plugin

Tạo Slide Ảnh Slick Carousel Cho WordPress Không Dùng Plugin

Yêu cầu đối với phương pháp này là bạn phải có hiểu biết cơ bản về code một chút, nếu không bạn sẽ hơi khó để áp dụng cách này.

1] Chèn thư viện Slick

Bạn vào trang chủ của Slick và tải về thư viện của nó, chèn vào website của mình. Các bạn có thể dùng trực tiếp thư viện của nó bằng CDN cũng đc.

2] Tạo Meta box để chèn hình ảnh vào bài viết

Bạn copy đoạn code bên dưới chèn vào functions của giao diện bạn đang dùng.

function add_hinhanh_metabox_up() {
      add_meta_box( 'my-post-box', 'THÊM SLIDE HÌNH ẢNH', 'add_hinhanh_metabox_up_post', 'post', 'normal', 'high' );
    }
    add_action( 'add_meta_boxes', 'add_hinhanh_metabox_up' );

    function add_hinhanh_metabox_up_post($post) {
      $banner_img = get_post_meta($post->ID, 'post_hinhanh', true);
      ?>
      <style type="text/css">
        .add_hinhanh_class ul li .delete-img {
          position: absolute;
          right: 3px;
          top: 2px;
          background: #333;
          border-radius: 50%;
          cursor: pointer;
          font-size: 14px;
          line-height: 20px;
          color: #fff;
        }
        .add_hinhanh_class ul li {
          width: 120px;
          display: inline-block;
          vertical-align: middle;
          margin: 5px;
          position: relative;
        }
        .add_hinhanh_class ul li img {
          width: 150px;
          height: 100px;
          object-fit: cover;
          object-position: 50% 50%;
          border-radius: 12px;
        }
        .button {
          margin-right: 10px !important;
        }
      </style>
      <div><?php echo add_hinhanh_metabox('post_hinhanh', $banner_img); ?></div>
      <script type="text/javascript">
        jQuery(function($) {
          $('body').on('click', '.them_hinhanh', function(e) {
            e.preventDefault();
            var button = $(this),
            custom_uploader = wp.media({
              title: 'Thêm hình ảnh',
              button: { text: 'Chọn' },
              multiple: true
            }).on('select', function() {
              var attech_ids = '';
              var attachments = custom_uploader.state().get('selection'),
              attachment_ids = new Array(),
              i = 0;
              attachments.each(function(attachment) {
                attachment_ids[i] = attachment['id'];
                attech_ids += ',' + attachment['id'];
                var imgHtml = '<li data-attechment-id="' + attachment['id'] + '"><a href="' + attachment.attributes.url + '" target="_blank"><img class="true_pre_image" src="' + attachment.attributes.url + '" /></a><i class=" dashicons dashicons-no delete-img"></i></li>';
                $(button).siblings('ul').append(imgHtml);
                i++;
              });
              var ids = $(button).siblings('.attechments-ids').attr('value');
              if (ids) {
                ids = ids + attech_ids;
                $(button).siblings('.attechments-ids').attr('value', ids);
              } else {
                $(button).siblings('.attechments-ids').attr('value', attachment_ids);
              }
              $(button).siblings('.xoa_tat_hinhanh').show();
            }).open();
          });

          $('body').on('click', '.xoa_tat_hinhanh', function() {
            $(this).hide().prev().val('').prev().addClass('button').html('Thêm ảnh');
            $(this).parent().find('ul').empty();
            return false;
          });

          jQuery(document).on('click', '.add_hinhanh_class ul li i.delete-img', function() {
            var ids = [];
            jQuery(this).parent().remove();
            jQuery('.add_hinhanh_class ul li').each(function() {
              ids.push(jQuery(this).attr('data-attechment-id'));
            });
            jQuery('.add_hinhanh_class').find('input[type="hidden"]').attr('value', ids.join(','));
          });
        });
      </script>
      <?php
    }

    function add_hinhanh_metabox($name, $value = '') {
      $image_str = '';
      $image_size = 'full';
      $display = 'none';
      $value = explode(',', $value);
      if (!empty($value)) {
        foreach ($value as $values) {
          if ($image_attributes = wp_get_attachment_image_src($values, $image_size)) {
            $image_str .= '<li data-attechment-id="' . $values . '"><a href="' . $image_attributes[0] . '" target="_blank"><img src="' . $image_attributes[0] . '" /></a><i class="dashicons dashicons-no delete-img"></i></li>';
          }
        }
      }
      if($image_str){
        $display = 'inline-block';
      }
      return '<div class="add_hinhanh_class"><ul>' . $image_str . '</ul><a href="#" class="them_hinhanh button">Thêm ảnh</a><input type="hidden" class="attechments-ids ' . $name . '" name="' . $name . '" id="' . $name . '" value="' . esc_attr(implode(',', $value)) . '" /><a href="#" class="xoa_tat_hinhanh button" style="display:' . $display . '">Xoá hết</a></div>';
    }

    function add_hinhanh_save($post_id) {
      if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
      if (!current_user_can('edit_post', $post_id)) return;
      if (isset($_POST['post_hinhanh'])) {
        update_post_meta($post_id, 'post_hinhanh', sanitize_text_field($_POST['post_hinhanh']));
      }
    }
    add_action('save_post', 'add_hinhanh_save');

Sau khi chèn vào, mối lần bạn tạo bài viết mới nó sẽ có một bẳng như thế này để bạn chèn ảnh vào.

them anh vao slide

Tiếp theo bạn thêm đoạn JS này vào website của bạn.

$('.slider-for').slick({
 slidesToShow: 1,
 slidesToScroll: 1,
 arrows: true,
 fade: true,
 asNavFor: '.slider-nav'
});
$('.slider-nav').slick({
  slidesToShow: 3,
  slidesToScroll: 1,
  asNavFor: '.slider-for',
  arrows: false,
  dots: false,
  focusOnSelect: true
});

$('a[data-slide]').click(function(e) {
 e.preventDefault();
 var slideno = $(this).data('slide');
 $('.slider-nav').slick('slickGoTo', slideno - 1);
});

3] Hiển thị slide ra giao diện

Bạn chèn code để hiển thị slide vào nơi bạn muốn hiển thị nhé.

<div class="col-12">
			<?php
			$id = get_the_ID();
			$banner_img = get_post_meta($id, 'post_hinhanh', true);
			$banner_img = explode(',', $banner_img);
			if (!empty($banner_img)) {
			?>
			<div class="slider slider-for">
			<?php foreach ($banner_img as $attachment_id): ?>
				<?php $img_url = wp_get_attachment_url($attachment_id); ?>
				<?php $img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); ?>
				<div><img src="<?php echo esc_url($img_url); ?>" alt="<?php echo esc_attr($img_alt); ?>"></div>
			<?php endforeach; ?>
			</div>

			<div class="slider slider-nav">
			<?php foreach ($banner_img as $attachment_id): ?>
				<?php $img_url = wp_get_attachment_url($attachment_id); ?>
				<?php $img_alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true); ?>
				<div><img src="<?php echo esc_url($img_url); ?>" alt="<?php echo esc_attr($img_alt); ?>"></div>
			<?php endforeach; ?>
			</div>
			<?php } ?>
			</div>

Sau khi làm xong những bước này, các bạn hãy tùy biến css theo ý mình để cho nó. Bạn có thể tham khảo tại đây nhé.

.slick-slide{padding:10px}
.slick-slide img{cursor:pointer}
.slick-track img{width:100%;height:145px;object-fit:cover;border-radius:5px}
button.slick-next.slick-arrow{background:#fff;right:25px;width:30px;height:30px;border-radius:5px}
button.slick-prev.slick-arrow{background:#fff;left:25px;z-index:1;width:30px;height:30px;border-radius:5px}
.slick-prev:before,.slick-next:before{color:#333;line-height:0.3;opacity:1}
.slick-prev:before{content:'‹';font-size:30px}
.slick-next:before{content:'›';font-size:30px}

DEMO SLIDE HOÀN CHỈNH

Có thể bạn quan tâm:

Theo dõi trên

Logo Google new
5/5 - (1 bình chọn)