rorschaff rorschaff - 3 months ago 11
CSS Question

How to use WP Dashboard to add/remove Carousel images?

I would like to know how I can code my WP Template files to give control over to the WP dashboard, to add or remove slider images. Example code below.

<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
<li data-target="#myCarousel" data-slide-to="3"></li>
<li data-target="#myCarousel" data-slide-to="4"></li>
</ol>
<!-- slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="<?php echo get_template_directory_uri() . '/images/slides/slide-01.jpg' ?>" alt="01">
</div>

<div class="item">
<img src="<?php echo get_template_directory_uri() . '/images/slides/slide-02.jpg' ?>" alt="02">
</div>

<div class="item">
<img src="<?php echo get_template_directory_uri() . '/images/slides/slide-03.jpg' ?>" alt="03">
</div>

<div class="item">
<img src="<?php echo get_template_directory_uri() . '/images/slides/slide-04.jpg' ?>" alt="04">
</div>

<div class="item">
<img src="<?php echo get_template_directory_uri() . '/images/slides/slide-05.jpg' ?>" alt="05">
</div>
</div>


I would like to be able to allow future WP editors to add/remove images in the carousel from the WP dashboard (e.g. customize) without having to edit the template files themselves. The code that would be dynamic above would be the likes of '/files/moreFiles/slide-XX.jpg'

I have found the answer to my question on this post, "HTML/Javascript: Iterate through all elements of local (server-side) folder"
HTML/Javascript: Iterate through all elements of local (server-side) folder

Answer

This thread asks and answers my question more broadly: "HTML/Javascript: Iterate through all elements of local (server-side) folder" HTML/Javascript: Iterate through all elements of local (server-side) folder

EDIT: All Below...

I have borrowed some code from the answer above and included it below where specified.

These are the steps to generate custom sliders in a WP setting.

  1. Create a folder in your images folder called 'sliders'
  2. Create the following files 'getimages.php', 'sliders-custom.php', and 'sliders.php'
  3. Add the following code block to your 'header.php' file:

    <?php session_start(); $_SESSION['se_template_dir'] = get_template_directory_uri(); $_SESSION['se_custom_sliders'] = 'generic'; ?>

  4. Go into your WP Dashboard-->Pages-->Some_Page, and a 'custom field' called: 'custom_sliders' (this is what is referenced above in the session variable)

  5. In your 'images/sliders/' folder, add folders corresponding to the names of your 'custom_sliders' field on your WP page. E.g. If your 'About' page has a 'custom_field' of value 'about', then you would add a folder in 'images/sliders/' called 'about' and then place images into it.

  6. Add the following code block to index.php, pages.php, single.php where you want your sliders to be;

    <?php
      $key_value = get_post_meta( get_the_ID(), 'custom_sliders', true );
      $_SESSION['se_custom_sliders'] = strtolower($key_value);
      //If 'custom_sliders' is empty, do nothing ('generic' is the default in the session variable, therefore 'images/sliders/generic/' will populate)
        if ( ! empty( $key_value ) ) {
          //If a 'generic' does not exist, WP will load 'sliders.php'
          //this is just a WP function to get(else 'A', 'B') it's BassAckwards is all
          get_template_part( 'images/sliders/sliders', 'custom' );
        }
    ?>
    
  7. Now let's setup the 'getimages.php' file; this file will scan the specified folder for images and populate an array to be sent to the JS block in 'sliders-custom.php':

    <?php
    session_start();
    
    $dir = strtolower($_SESSION['se_custom_sliders']);
    
    //This array will hold all the image addresses
    $result = array();
    
    //Get all the files in the specified directory
    $files = scandir($dir);
    
    foreach($files as $file) {
      switch(ltrim(strstr($file, '.'), '.')) {
       //If the file is an image, add it to the array
       case "jpg": case "jpeg":case "png":case "gif":
       $result[] = $_SESSION['se_template_dir'] . "/images/sliders/" . $dir . "/" . $file;
      }    
    }
    
    $_SESSION = array();
    
    if (ini_get("session.use_cookies")) {
      $params = session_get_cookie_params();
      setcookie(session_name(), '', time() - 42000,
      $params["path"], $params["domain"],
      $params["secure"], $params["httponly"]
      );
    }
    
    //Kill the session unless you have reason to retain the populatedvariables
    session_destroy();
    
    //Convert the array into JSON
    $resultJson = json_encode($result);
    //Output the JSON object
    //This is what the AJAX request will see
    echo($resultJson);
    ?>
    
  8. Next, set up 'sliders-custom.php':

    <!-- All classes below are from BOOTSTRAP -->
    <div id="carousel-container">
      <div class="container">
        <div id="myCarousel" class="carousel slide" data-ride="carousel">
    
      <!-- Indicators -->
      <ol id="inject-slider-indicators" class="carousel-indicators">
        <!-- Slider Indicators are injected here, and paired with sliders below by numbers (0 - x) -->        
      </ol>
    
      <div id="build-sliders" class="carousel-inner" role="listbox">         
        <!-- Sliders are appended here via JS below -->       
     </div> 
    
      <!-- Left control -->
      <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
      </a>
      <!-- Right control -->
      <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
      </a>
    </div>
    

On this same page, below the HTML (above), add the following JS:

<script>
//The div element to hold the sliders
var imageContainer = document.getElementById("build-sliders");
//Makes an asynch request, loading the getimages.php file
function callForImages() {
    //Create the request object
    var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
    //When it loads,
    httpReq.onload = function() {
        //Convert the result back into JSON
        var result = JSON.parse(httpReq.responseText);
        //Show the images
        loadImages(result);
    }
    //Request the page
    try {
        httpReq.open("GET", <?php echo '"' . get_template_directory_uri() . '/images/sliders/getimages.php"'; ?>, true);
        httpReq.send(null);
    } catch(e) {
        console.log(e);
    }
}
//Generates the images and appends them to the container
function loadImages(images) {
    //For each image,
    for(var i = 0; i < images.length; i++) {
        //Make a new image element, for each image in folder
        //specified by the 'custom_sliders' variable            
        $('<img/>', {
            id: 'slider-' + i,    
            class:  'item',
            src: images[i],
            alt: 'slider image ' + i
        }).appendTo('#build-sliders');

        $('<li></li>', {
            id: '#slider-ind-' + i,
            'data-target': '#myCarousel',    
            'data-slide-to':  i
        }).appendTo('#inject-slider-indicators');          
    }      
  //Make the first slider 'active'
  $('#slider-0').addClass('active');
  //Make the first slider-indicator 'active'
  $('#slider-ind-0').addClass('active');      
}
callForImages();
</script>

Big thanks to @Jeffrey_Sweeney for his post at http://stackoverflow.com/a/13595180/5636972