How To Create A Responsive Image Slider

How To Create Dynamic And Responsive Image Slider In PHP

How To Create Dynamic And Responsive Image Slider In PHP

In this tutorial i will teach You How To Create Dynamic And Responsive Image Slider In PHP.We are using MySQL as back-end.For this we are using FlexSlider and CSS3.To start with it we have to create a table in MySQL.In this example we have one column for storing image name, you can also use slider sequence to display the slides according to sequence.

Config.php:

PHP Code:

  • ?>
  • HighTechnology.in | Hosting Partner Grootstech Solutions

    StyleSheet:

    body < margin:0px auto; font-family:Candara; font-size:14px; width:100%; >.h2 < text-align:center; >.footer < width: 100%; text-align: center; padding-top: 40px; font-size: 16px; >.container < width:80%; min-width: 150px; max-width: 960px; margin:0px auto; text-align:center; >.container a:active, .flexslider a:active, .container a:focus, .flexslider a:focus < outline: none; >.slides, .flex-control-nav, .flex-direction-nav < margin: 0; padding: 0; list-style: none; >.flexslider a img < outline: none; border: none; >.flexslider < margin: 0; padding: 0; position: relative; zoom: 1; padding: 10px; background: #ffffff; >.flexslider .slides > li < display: none; backface-visibility:hidden; -webkit-backface-visibility: hidden; >.flexslider .slides img < width: 100%; display: block; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; >.slides:after < content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; >html[xmlns] .slides < display: block; >* html .slides < height: 1%; >.flexslider .slides < zoom: 1; >.flex-direction-nav a < display: block; position: absolute; margin: -17px 0 0 0; width: 35px; height: 35px; top: 50%; cursor: pointer; text-indent: -9999px; background-color: #ff6a00; >.flex-direction-nav a:before < display: block; position: absolute; content: ''; width: 9px; height: 13px; top: 11px; left: 11px; background: url(image/arrows.png) no-repeat; >.flex-direction-nav a:after < display: block; position: absolute; content: ''; width: 0; height: 0; top: 35px; >.flex-direction-nav .flex-next < right: -5px; -webkit-border-radius: 3px 0 0 3px; -moz-border-radius: 3px 0 0 3px; border-radius: 3px 0 0 3px; >.flex-direction-nav .flex-prev < left: -5px; -webkit-border-radius: 0 3px 3px 0; -moz-border-radius: 0 3px 3px 0; border-radius: 0 3px 3px 0; >.flex-direction-nav .flex-next:before < background-position: -9px 0; left: 15px; >.flex-direction-nav .flex-prev:before < background-position: 0 0; >.flex-direction-nav .flex-next:after < left: 20px; border-bottom: 5px solid transparent; border-left: 12px solid #ff6a00; >.flex-direction-nav .flex-prev:after < left: 0; border-bottom: 5px solid transparent; border-right: 16px solid #ff6a00; >.flexslider .flex-control-nav < position: absolute; width: 100%; bottom: -40px; text-align: center; margin: 0 0 0 -10px; >.flex-control-nav li < display: inline-block; zoom: 1; >.flex-control-paging li a < display: block; cursor: pointer; text-indent: -9999px; width: 12px; height: 12px; margin: 0 3px; background-color: #b6b6b6 \9; -webkit-border-radius: 12px; -moz-border-radius: 12px; border-radius: 12px; -webkit-box-shadow: inset 0 0 0 2px #b6b6b6; -moz-box-shadow: inset 0 0 0 2px #b6b6b6; box-shadow: inset 0 0 0 2px #b6b6b6; >.flex-control-paging li a.flex-active

    How To Create Dynamic & Responsive Image Slider In PHP

    Источник

    Как создать слайдер из изображений, загруженных в пост?

    После того, как в WordPress изменился загрузчик изображений, его стало удобнее использовать для других различных целей, то есть не только для загрузки изображений в пост .

    Например для создания галерей или слайдеров. Слайдер мне кажется наиболее интересным, поэтому давайте попробуем реализовать его на стандартной вордпрессовской теме, например TwentyEleven.

    изображения, загруженные к посту

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

    Создание слайдера в 4 шага

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

    Ниже пример такого слайдера с одного из созданных мной сайтов:

    слайдер с сайта 56thparallel

    Можете кликнуть по изображению и посмотреть на него в действии.

    Итак, для создания слайдера нам само собой понадобится какой-нибудь jQuery-плагин, я буду использовать бесплатный Nivo Slider, вы же можете взять что-нибудь другое.

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

    • nivo-slider.css — CSS стили, необходимые для корректного отображения слайдера,
    • jquery.nivo.slider.pack.js — собственно сам jQuery-плагин.

    Шаг 1. Подключение необходимых файлов

    Прежду всего вы должны убедиться в том, что в шапке сайта задействована функция wp_head(), а в футере wp_footer(). Если этих функций там нет, то добавьте, иначе не рассчитывайте, что всё будет работать, как надо.

    Итак, помещаем скачанные файлы в папку с темой (например), после этого воспользуемся функциями wp_enqueue_script() и wp_enqueue_style().

    Вставляем следующий код в functions.php , который находится в папке с темой:

    add_action( 'wp_enqueue_scripts', 'true_scripts_and_styles_for_slider' ); function true_scripts_and_styles_for_slider() { wp_enqueue_style( 'nivocss', get_stylesheet_directory_uri() . '/nivo-slider.css' ); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'nivojs', get_stylesheet_directory_uri() . '/jquery.nivo.slider.pack.js', array('jquery'), null, true ); }

    Содержимое файла nivo-slider.css можно засунуть внутрь стандартного style.css, в этом случае 4-ю строчку из предыдущего листинга можно удалить или закомментировать.

    Шаг 2. Определяемся с размерами слайдера

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

    После этого открываем functions.php и вписываем туда следующую строку:

    add_image_size( 'trueslider', 640, 480, true ); // где 640 это ширина, а 480 - высота слайдера

    Это нужно для того, чтобы при загрузке изображения, WordPress автоматически генерировал копию соответствующих размеров непосредственно для слайдера.

    Шаг 3. Выводим изображения в слайдер

    Открываем необходимый нам PHP-файл, в котором будет выводиться слайдер, например у меня это шаблон обычного поста single.php .

    // массив параметров вывода изображений $args = array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'orderby' => 'menu_order', // сортировка, menu_order - по выставленному в админке порядку, можно также сортировать по имени или дате добавления 'order' => 'ASC', 'numberposts' => 5, // количество выводимых изображений 'post_mime_type' => 'image' ); if ( $images = get_children( $args ) ) { // если никаких изображений в пост не добавлено, то не выводим вообще ничего echo '
    // не забудьте указать свои значения ширины (640) и высоты (480) foreach( $images as $image ) { echo wp_get_attachment_image( $image->ID, 'trueslider' ); } echo '
    '
    ; }

    Читайте подробнее про функцию get_children().

    После добавления этого кода зайдите на страницу редактирования какого-нибудь поста и загрузите туда несколько изображений (вставлять в редактор поста их ни к чему, просто загружаем через загрузчик).

    Шаг 4. Активируем слайдер.

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

    Кроме того, так как это JavaScript-код, то не забываем затолкать его в HTML-теги .

    jQuery(function($){ $('#slider').nivoSlider({ effect: 'random', // эффекты, например: 'fold, fade, sliceDown, sliceDownLeft, sliceUp, sliceUpLeft, sliceUpDown, sliceUpDownLeft, slideInRight, slideInLeft' animSpeed: 500, // скорость анимации pauseTime: 3000, // пауза между сменой слайдов directionNav: true, // нужно ли отображать кнопки перехода на следующий и предыдущий слайд controlNav: true, // 1,2,3. навигация (например в виде точек) pauseOnHover: true, // останавливать прокрутку слайдов при наведении мыши manualAdvance: false, // true - отключить автопрокрутку prevText: 'Назад', // текст перехода на предыдущий слайд nextText: 'Вперед', // текст кнопки перехода на следующий слайд randomStart: false, // начинать со случайного слайда }); });

    Миша

    Впервые познакомился с WordPress в 2009 году. Организатор и спикер на конференциях WordCamp. Преподаватель в школе Нетология.

    Пишите, если нужна помощь с сайтом или разработка с нуля.

    Источник

    How to create dynamic, responsive image slider with PHP, mysqli, bootstrap and jQuery ?

    Description :- In this lesson I’m gonna provide the code from which you guys can easily make fully Dynamic Carousel Silder from which you’ll fetch image name from database and images from your img folder.

    Establishing Database:-
    Now, I know that you all guys know how to create new database and name it slider after this create new table and name it images and make 2 rows
    (i) id
    (ii) img
    And then insert your image name with extension into the img row .

    Now follow some simple steps for setting up everything which we need for this lesson:-
    1. Download the bootstrap
    2. Download jquery file from jquery.com
    2. Create a new folder and rename it as img and put some images in it.
    3. Create a new folder and rename it as css and make app.css in the css folder
    4. Create an index.php file
    5. Create config.php file (the connection file to our database)

    1. config.php (the connection file)

    2. index.php (the file where your silder code lives with some jquery lines)

    There are some problems with wordpress text editor so I’m providing pdf of index.php copy from pdf and make index.php
    Copy code from this link

    3. app.css (lives in css folder)

    a.carousel-control < opacity: 1; height: inherit; width: inherit; background: none; text-shadow: none; >.prevSlide < color: #f5f5f5; font-size: 2em; position: absolute; top: 50%; left: 0; background-color:rgba(0,0,0,0.5); transform: translate(0,-50%); padding: 0 10px; >.prevSlide:hover < color:rgba(247,148,30,1); background-color:rgba(0,0,0,0.8); >.nextSlide < color: #f5f5f5; font-size: 2em; position: absolute; top: 50%; right: 0; background-color:rgba(0,0,0,0.5); transform: translate(0,-50%); padding: 0 10px; >.nextSlide:hover

    *Note:- My final product screenshot is this except the images in the slider you will get the same result.

    Источник

    How to Create Dynamic Image Slider Using PHP and Bootstrap

    Create Dynamic Slider using PHP

    Vivek Moyal

    How to create dynamic image slider using php and bootstrap this is the topic of our new tutorial and this tutorial is dedicated to the mails which i have received over my email from long time.

    I have also created 2 video’s regarding How to create dynamic slider in PHP over youtube. Or you can view the video below.

    You can find more PHP Tutorials Videos at my channel over Youtube. Lets start with the article.

    In this article we will create a simple image upload script and a page where we will show the slider using the PHP script. For showing the dynamic image slider i have used the Bootstrap carousel. I will divide this article in 2 parts 1 is for uploading the image using the php and html form and another is for showing the slider. Lets start with the part 1.

    How to upload images using PHP and HTML Form

    For uploading the image i have created a very simple form with 3 text boxes –

    1. File type input for Image
    2. Text box input for showing the bold text
    3. Text box input for showing the small text

    Why we use bold and small text ? It is because many time we want to show some text over the images of the slider. So that i have created the textboxes through which we can achieve the same effect.

    For uploading the image to the server i have used the PHP upload script on submit click. Below script will just save the image to the server and sends the value to the sliderClass.

    if(isset($_POST["submit"])) < $getImage= basename($_FILES["Image"]["name"]); if($getImage=="")< echo "Please choose"; >else < $target="../sliderImage/"; $ran=time(); $target=$target.$ran.$getImage; $imageName=$ran.$getImage; if($_FILES["Image"]["type"]=="image/jpg"||$_FILES["Image"]["type"]=="image/jpeg")< move_uploaded_file($_FILES["Image"]["tmp_name"], $target); if(move_uploaded_file)< include_once './slider/sliderClass.php'; $sliderClass=new SliderClass(); $sliderClass->uploadSlider($imageName,$_POST["Big"],$_POST["Small"]); > else < echo "File is not uploaded"; >> else < echo "Please choose Image"; >> >

    sliderClass.php – This class is used for saving the image value to the database and for showing the list of images over the slider. For saving the image name we have used the uploadSlider function which will take 3 parameters Image, Bold text and Small text.

    public function uploadSlider($image,$big,$small)< $insert="Insert into slider (ImageName,BigText,SmallText) values ('$image','$big','$small')"; $result=$this->query($insert); if($result) < echo "File is uploaded"; >else < echo "File is not uploaded"; >>

    How to show the images slider using PHP and Bootstrap

    You can download the whole code at the bottom of the post. Now its the time for setting up the slider to show the images. For this i have used the Bootstrap carousel with the PHP foreach loop for showing all the images in slider. In the below code you will see 2 times we have used the foreach loop. One is for showing the bullets over the slider and another is for showing the images.

    For showing the images we have used listSlider function which is written in our sliderClass.

    public function listSlider()< $select="select * from slider"; $result=$this->query($select); $count=$result->num_rows; if($count < 1)< >else < while ($row = $result->fetch_array()) < $rows[]=$row; >return $rows; > >

    Database Table

    CREATE TABLE IF NOT EXISTS `slider` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `ImageName` varchar(250) NOT NULL, `BigText` varchar(250) NOT NULL, `SmallText` varchar(500) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

    In this article you will see that we have completed many questions like –

    • How to upload image in PHP
    • How to show images dynamically in php
    • How to create dynamic slider in php
    • How to get images from database and use them in Slider.

    Many questions like these are there. Hope we have solved your queries if you have any issue please comment below. If you want to share any doubt or error than please comment below.

    You can also watch the video series over this topic at my Youtube Channel. You can also download the whole code regarding the tutorial.

    Источник

    Читайте также:  Python print no line ending
    Оцените статью