Adding WordPress Posts using Ajax

Many WordPress themes and plugins come with some demo data (posts and pages) which the users can install when they activate the plugin. These WordPress posts and pages are designed to give the users a head start on setting up the theme or plugin and give them some readily available dummy data to play with.

In the Chamber Dashboard plugins, although we have extensive documentation and a couple of demo sites for users to see, it is still not easy for some users to visualize how their business directory page would look like with their theme. So, we decided to add some demo content that the users will be able to install when they activate the Business Directory plugin for the first time on their site.

Buttons to add demo data

The demo data buttons show up in a modal on the welcome page. The modal is displayed using the jQuery .dialog() function.

$("#demo_content_buttons").dialog({
    modal: true,
    buttons: [
    {
      text: "Ok",
      click: function() {
        $( this ).dialog( "close" );
      }
    }
  ]
  });

Here is the html for adding the demo data buttons. The “loader” div will show when the data is being added and when it is done, the message will show in the success_message div. Initially the loader div is hidden using jQuery.

 
function cdash_install_demo_content_button(){
  ?>
  <div id="demo_content_buttons">
    <p>Welcome to the Business Directory plugin! Install demo content now, then check out the Business Directory page to see a sample Directory, or dismiss this notice to get started with uploading your own listings.</p>
    <p class="demo_content button cdash_admin button-primary">Install Demo Content</p>
    <p class="demo_content_decline button cdash_admin button-primary">No Thanks!</p>
    <p id="loader">Loading...</p>
    <p class="cdash_demo_success_message"></p>
  </div>
  <?php
}
$("#loader").css("display", "none");

Setting a Transient

One of the basic requirements of this feature is that the demo data install buttons should only show up when the users install and activate the plugins for the first time. Users who have been already using it, should not see it when they update their plugin to the new version. So, to take care of these two scenarios, I added a transient. The transient would get set to true the first time the plugin is activated. The demo data buttons would show only if the transient is not set.

//If plugin is activated for the first time, set the transient
function cdash_show_demo_buttons(){
  //$demo_content_install = get_transient('cdash_demo_content_install');
  if(false === get_transient('cdash_demo_content_install')){
    //show the Install Demo Content button
    cdash_install_demo_content_button();
  }
  set_transient('cdash_demo_content_install', 'true');
}

The transient is also set to true if the plugin is updated. This ensures that if the user is just updating the plugin, they will not see the popup asking them if they want to install demo data.

function cdash_set_demo_transient(){
  set_transient('cdash_demo_content_install', 'true');
}
add_action( 'upgrader_process_complete', 'cdash_set_demo_transient');

Ajax call for the demo data

The actual demo data will be added via Ajax call that gets triggered when the ‘Install’ button is clicked.

$(".demo_content.button").click(function(event){
    event.preventDefault();
    $.ajax({
      url: ajaxurl,
      type:'post',
      data: {
        'action': 'cdash_add_demo_data',
      },
      beforeSend: function() {
        $('#loader').show();
        $(".demo_content_decline").hide();
      },
      complete: function(){
         $('#loader').hide();
         $(".dashboard_page_cdash-about .ui-dialog-buttonpane").show();
      },
      success: function(response){
        $(".cdash_demo_success_message").html(response);
      },
    });
  });

The Ajax function calls the cdash_add_demo_data() function. That function adds the business categories, the demo businesses and a couple of demo pages. If the page or post already exists, it will not be created again.

function cdash_add_demo_data(){
  $response = '';

  //Create demo business categories
  cdash_demo_bus_categories();

  //Creating demo businesses
  $demo_post_id = cdash_insert_demo_business();

  //Creating demo pages
  $demo_page_id = cdash_add_demo_pages();

  //Check if there the post or page exists
  if ( ($demo_post_id != 0) || $demo_page_id !=0 )
    {
       //If post or page does not exists
        $response = 'Demo data successfully added.';
    }
    else {
	//Post or page exists
        $response = 'The data already exists.';
    }
    // Return the String
    die($response);
}

// creating Ajax call for WordPress
add_action( 'wp_ajax_cdash_add_demo_data', 'cdash_add_demo_data' );

Let’s look at the add demo content function in a little bit more detail. The categories are added using the wp_insert_term(). The function to add business categories checks to see if the category already exists so as to avoid any duplicate categories.

The next step is to add the businesses. The demo content is in an array. The demo button will install 3 new posts to the custom post type ‘business’. The first step is to create the post object.

// Create post object
  $demo_content = "Create a description for your business here, or install the Member Updater plugin so your members can update their own listings!";

  $demo_bus_data = array(
    array (
      'title' => 'Karleton’s Bakery',
      'content' => $demo_content,
      'post_category' => 'Restaurants',
      'featured_image' => 'images/demo_content/bakery_photogy-karlis-dambrans.jpg',      
    ),
    array (
      'title' => 'Wong’s Coffee & Tea',
      'content' => $demo_content,
      'post_category' => 'Restaurants',
      'featured_image' =>'images/demo_content/coffee_shopphotoby-jason-wong.jpg',
    ),
    array (
      'title' => 'Brendon’s Camera',
      'content' => $demo_content,
      'post_category' => 'Retail Shops',
      'featured_image' =>'images/demo_content/camera_shop_photoby-brendan-church.jpg',
    ),
  );

The next step is to loop through the post object and insert the post.

foreach ($demo_bus_data as $bus_demo) {
    if ( post_exists( $bus_demo['title'] ) ) {
      $demo_post_id = 0;
    }else{
      //post exists
      $add_pages = array(
          'post_title' => $bus_demo['title'],
          'post_content' => $bus_demo['content'],
          'post_status' => 'publish',
          'post_type' => 'business'
      );

      // Insert the post into the database
      $demo_post_id = wp_insert_post( $add_pages );

Then the category for the post needs to be set.

 wp_set_object_terms( $demo_post_id, $bus_demo['post_category'], 'business_category', $append );

Since the demo data was for a business directory, I wanted to add featured images for the demo businesses. I added the images in a folder inside the plugin and generated an image url from the path. The url and the post_id are used to upload the image to the media library and add it to the post. the cdash_insert_attachment_from_url() uses the code from
https://gist.github.com/m1r0/f22d5237ee93bcccb0d9 to add the featured image.

//attach the image files as featured image for each post
      $getImageFile = plugins_url( $bus_demo['featured_image'], dirname(__FILE__) );
      $url = $getImageFile;
  
      $attach_id = cdash_insert_attachment_from_url($url, $demo_post_id);
  
      set_post_thumbnail( $demo_post_id, $attach_id );

The entire code to insert the demo business with content and the featured image.

function cdash_insert_demo_business(){
  //Code to create a post with demo data
  global $wpdb;
  $user_id = get_current_user_id();
  // Create post object
  $demo_content = "Create a description for your business here, or install the Member Updater plugin so your members can update their own listings!";

  $demo_bus_data = array(
    array (
      'title' => 'Karleton’s Bakery',
      'content' => $demo_content,
      'post_category' => 'Restaurants',
      'featured_image' => 'images/demo_content/bakery_photogy-karlis-dambrans.jpg',      
    ),
    array (
      'title' => 'Wong’s Coffee & Tea',
      'content' => $demo_content,
      'post_category' => 'Restaurants',
      'featured_image' =>'images/demo_content/coffee_shopphotoby-jason-wong.jpg',
    ),
    array (
      'title' => 'Brendon’s Camera',
      'content' => $demo_content,
      'post_category' => 'Retail Shops',
      'featured_image' =>'images/demo_content/camera_shop_photoby-brendan-church.jpg',
    ),
  );

  foreach ($demo_bus_data as $bus_demo) {
    if ( post_exists( $bus_demo['title'] ) ) {
      $demo_post_id = 0;
    }else{
      //post exists
      $add_pages = array(
          'post_title' => $bus_demo['title'],
          'post_content' => $bus_demo['content'],
          'post_status' => 'publish',
          'post_type' => 'business'
      );

      // Insert the post into the database
      $demo_post_id = wp_insert_post( $add_pages );

      wp_set_object_terms( $demo_post_id, $bus_demo['post_category'], 'business_category', $append );

       //attach the image files as featured image for each post
      $getImageFile = plugins_url( $bus_demo['featured_image'], dirname(__FILE__) );
      $url = $getImageFile;
  
      $attach_id = cdash_insert_attachment_from_url($url, $demo_post_id);
  
      set_post_thumbnail( $demo_post_id, $attach_id );
  }
  }
  return $demo_post_id;
}

After the posts are added, two new pages are also added. The pages are added similar to the posts except the ‘post_type’ would be ‘page’ instead of ‘business’ which is a custom post type. Since there are no categories or featured images for the pages, it is just creating the post object and looping through it to add the pages. The function also checks to see if the pages already exists so as to avoid duplicate pages.

Adding custom CSS and JS to your WordPress site

WordPress provides many different ways to customize your site. You can build a custom theme that is unique to your site or you can use an existing theme and tweak it to suit your needs and style.

In all these years of working with WordPress, I have had countless occasions when I had to add a little custom code to the site. If you are a web developer, then this does not seem like an issue at all. You just know where to add the relevant code and you also know how to troubleshoot it if it does not work.

For those of you who are not quite the developers, but would like to have fun with your site, WordPress makes it easy to add code snippets. There are many different ways to add custom CSS or JavaScript to your site. You can use a plugin, or the customizer (only for CSS) or dive into creating a child theme and get your hands dirty with some coding. Whatever method you choose, there are lots of options and good documentation to get you through.

Using the Customizer to add custom CSS:

The Customizer has been part of WordPress for a while now and we have all got used to adding CSS quickly. Go to Appearance -> Customize. In the customizer, there is an option for ‘Additional CSS’. Click on that and add all the CSS you need and save. This is by far the easiest way to add custom CSS to your theme.

This method is good if you need to change or tweak a couple of things on your site. If you want to add CSS for many sections on the site, using a child theme is better.

There is no option to add custom JavaScript in the customizer with the default WordPress theme.  You will have to use some plugins. Some other themes might provide this feature.

Plugins for adding custom CSS and JS

There are a number of plugins that let you add custom code snippets to customize your site.

Custom Header Footer Scripts for Customizer enables you to add scripts to the header and footer of your theme via the customizer.

Simple Custom CSS and JS is my favorite one of all. It makes it very easy to add custom code and has a lot of features even in the free version. It also has options to add custom HTML.

CSS Hero is another plugin that can be used to tweak the CSS of your theme. This premium plugin lets you customize your site live. It gives you an easy interface to edit and see the changes as you are making them.

Using a child theme

There a lot of WordPress themes that you can use to build your site. Each theme gives you certain functionalities along with a certain look/design. If you choose a theme, that gives you the features you want for your site, but would like to change the look and style of it, child themes are best way to do it.

You can use child themes to use the functionality of the parent theme, but change the look and styles of your site. You can add/remove some functionality through the child theme if you like. Creating a child theme requires some knowledge of coding. There are some great tutorials that will guide you though the process of creating a child theme.

Here are some useful links for creating child themes.

Once you have a child theme in place, you can add new CSS and Js files by adding them to the child theme’s functions.php. You need to properly enqueue them.

Importance of strong online presence for small businesses

A couple of weeks ago, on our way back from the beach, we decided to go to an Indian restaurant for dinner. We wanted to try a new place. So, I started googling for restaurants near us and started checking out the ones that we could try. I wanted to check out their menu to see if they had a particular dish that my kids wanted to have. To my surprise, two or three of them did not have a website and even if they did, they did not have a proper menu.

This made me think why wouldn’t somebody who is doing business, not have a proper website? In this day and age, a website is very important for the success of your business. It can make or break a business.

Let’s take the example of restaurants. If they have a website with their menu and hours on it, it would be helpful to a lot of people. People are in a rush trying to find things quickly. People use ‘Siri’ and Google to find things online. If you do not have an online presence, they will not find you. You need to optimize your site to show up in the “near me” searches. Having your business address registered in Google search is not enough. You need to have a website and at least a couple of social media profiles that talk about you and your business.

Wider Audience

Having an online presence helps you gain wider audience. Your website is accessible to people around the world. You might think that your products/services are local, but never underestimate the power of the web. Even if it is local, your site will help you gain more customers. People usually tend to search for products and services online first. Even if you don’t sell anything online, your potential customers will checkout your site and if they like what they see, they might actually come to the store to buy the products or contact you for your services.

Website accessible at all times

Your website is accessible to people even when your office/store is closed. People don’t have the time to go and visit different stores before buying a product. Many of them prefer online shopping in the comfort of their homes. So, having a website means that your will show up as an option for your potential clients.  Some services cannot be bought online and in that case give your potential clients a chance to read about you and get to know you. That will make it easy for them to make the decision to hire you.

One of the reasons people ignore their websites and social media is because they do not know where to start. There is so much information thrown towards us, that we are utterly confused on what is important. 

Here are the three main things a business needs to thrive online. These are just the starters, but can quickly evolve into much more. 

  1. A website
  2. Social media presence
  3. Strong SEO

Websites

Setting up a website is one of the easiest things and also one of the first things you should do. Here are the things you need to setup a site:

  1. Domain Name 
    As soon as you decide on your business name, check if you can purchase a domain name the same as your business. If your business name is a unique one, then it should be easy. You can do a search for domain names easily – https://www.name.com/domain/search
  2. Hosting 
    Once you have the domain name, purchase a hosting account to host your website. You can find some good hosting options here. I use SiteGround for my site and recommend it for my clients as well. Their customer service is excellent. You can check out Site Ground’s hosting options here.
  3. CMS 
    Using a Content Management System like WordPress will make it easier to add new content and maintain your site in the long term. Although WordPress is easy, there might be a learning curve. Once you install WordPress on your site, you can add pages and content to your site. There will be some options to customize your site. You now have a brand new site that you can show off to the world!! 
  4. Design for your site: WordPress comes with a number of themes to choose from for the look of your site on the front end.  You can choose a free theme and setup your site. If you want a custom design for your site, you will need to hire a professional to help you with the design and the building of the theme. Here are some tips to choosing the right theme for your WordPress site.

Building a website isn’t rocket science, but there are some things to keep in mind while you are building or setting up your site.

Websites make lasting impressions on people. You have a few minutes to make them interested in your products/services. So, you should make sure that your brand value/personality shows through your website. That will help people make the connection between you, your products/services and your website. Make the website easy to use and have the information easily accessible.

Your website should speak about you and your business just like you would in person. Your website is one of the best resources you have to convince users to purchase your products/services.

How much do I spend on my website?

So, now the big question that bothers every small business owner – How much should I spend on my website? Unfortunately, there is no magic number anybody can give you. You have to figure it out based on your requirements.

The good news is that you do not need to put down an enormous amount for a starter website. 

Just like you would not start a company with 10,000 employees on day 1, you do not need an expensive website with all the bells and whistles to get started. You can have a starter website for about $2,000.00. As your business grows, you can add more features to your site.

Does my website need a re-design?

Social Media

Social media is as important as a website. People like to engage and get updates and information through their Facebook, Twitter, Instagram and other social media accounts. Having these for your business will definitely increase your customer base and result in more sales. Social media channels are a place where you can interact with your clients.

You do not need to have a profile on every social media channel out there. Some social media are preferable for some businesses. Facebook and Twitter are generally relevant to all businesses. There are other social media channels like Instagram, YouTube, LinkedIn, Pinterest etc which you should definitely look into.

Post about product updates, offers, new products etc on your social media. Make it so that your potential customers are guided back to your website from all the social media channels.

SEO

Search Engine Optimization ensures that your site will show up on major search engines. Most people end up on a site from search engines. If your site does not show up in a search, it is very likely that you won’t be found on the internet. 

SEO is an ongoing process. You have to keep working on it to make sure your site shows up for relevant searches. If you use WordPress, there are a number of free plugins that will help you with SEO. I use the Yoast SEO plugin which offers a number of options even in the free version.

You can dedicate entire days for your SEO and there will be still so much more you can do. But, since you also need to focus on your business, you can start with a few things and learn as you go.

  • Add your site to the Google Search Console and the Bing webmaster tools. The webmaster tools help you see how your site is showing up on search engines, how your pages are ranking and what search phrases or words are people using to land on your pages. You can use the free Yoast SEO plugin for this.
  • Add an XML sitemap. XML sitemap is like a table of contents for your site. This helps search engines crawl all the pages on your site more efficiently. Sitemaps also include information about when the pages have been updated and the meta data of the pages.
  • Make sure your pages are loading quickly. If you have great content on your site, but it takes forever for your pages to load, people will quickly leave the site.
  • Have a mobile friendly site. Most of the website traffic these days comes from mobile phones and tablets. So, making your site mobile friendly is very important.
  • Optimize your page content and images – There is a lot you can do to optimize the content of your pages. Get started by having a title and description for your pages. This can be done using the Yoast SEO plugin if you are using WordPress. Adding descriptions to images using the alt tags and optimizing the image sizes helps.

There is a lot more you can do to have a strong online presence for your business. Get started with the minimum and add as you build your business online.

Get tips and tutorials on using the new block editor, WordPress themes and plugins!

Adding line items to WooCommerce

I have been working on integrating the Chamber Dashboard plugins with WooCommerce (WC) to give our users payment options other than PayPal. As part of this WC integration, I have had to create products, orders and add line items to the orders to show the custom information coming in from our plugins. Although there is a ton of documentation when it comes to WC, I had to struggle to get the line items added correctly. This was especially difficult because the orders were being created from the admin side and not by the user.

There is a front end form that comes with the Member Manager plugin that users use to either register their business for the first time or renew their businesses with the Chambers. Either way, when they fill out the form, there is an invoice being created on the back end which gets sent to the user who would pay with either a check or using PayPal.

Since we are replacing PayPal with whatever payment options are set in WC, the users will be taken to the order page when they submit the form. When the chambers decide to use WC payments, an order gets created along with the invoice when the form is filled. But this order by default only has the product information (products here are the membership levels that have been already set).

Why are line items needed here?

The chambers can choose to add processing fee, tax, or donation amount fields to the front end form, which need to be added to the WC order as well. These numbers usually change for each order, so they have to be added to the order when the order is created (when the front end form is filled out). Fortunately, WC has an easy way of adding line items to the orders using the function wc_add_order_item().

Below is the function used to add an order in WC. As part of that process, wc_add_order_item() is called which creates the line items with the information from the form.

Creating a new order in WooCommerce

//Create a new order in WooCommerce
function cdashmm_create_wc_order($address, $product_id, $total, $customer_id, $donation, $tax, $processing_fee){
	if(cdashmm_check_mm_connected_to_wc()){
		global $woocommerce;
        $args = array(
            'customer_id'   => $customer_id,
            'created_via'   => 'Chamber Dashboard Recurring Payments',
            'add_order_note' => 'Created via Chamber Dashboard Member Manager');

        // Now we create the order
        $order = wc_create_order($args);

        // The add_product() function below is located in /plugins/woocommerce/includes/abstracts/abstract_wc_order.php
        $order->add_product( wc_get_product($product_id), 1); // This is an existing SIMPLE product
        $order->set_address( $address, 'billing' );
        $order->set_created_via(  $args['created_via'] );
        $order->add_order_note( $args['add_order_note'] );
	$order->set_total( $total );
	$order->update_status("Completed", 'Imported order', TRUE);
      	$order_id = $order->get_id();

        if($donation){
	    $item_id = wc_add_order_item($order_id, array('order_item_name'	=>	__('Donation', 'cdashmm'), 'order_item_type'	=>	'fee'));
	    if ($item_id) {
	 	wc_add_order_item_meta($item_id, '_line_total', $donation);
	 	wc_add_order_item_meta($item_id, '_line_tax', 0);
	 	wc_add_order_item_meta($item_id, '_line_subtotal', $donation);
	 	wc_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
	 	//wc_add_order_item_meta($item_id, '_tax_class', 'zero-rate');
	 }
}
		if($processing_fee){
		      $item_id = wc_add_order_item($order_id, array('order_item_name'	=>	__('Processing Fee', 'cdashmm'), 'order_item_type'	=>	'fee'));
		if ($item_id) {
	 	       wc_add_order_item_meta($item_id, '_line_total', $processing_fee);
	 		wc_add_order_item_meta($item_id, '_line_tax', 0);
	 		wc_add_order_item_meta($item_id, '_line_subtotal', $processing_fee);
	 		wc_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
	 		//wc_add_order_item_meta($item_id, '_tax_class', 'zero-rate');
	 		}
}
       if($tax){
         $item_id = wc_add_order_item($order_id, array('order_item_name' => __('Tax', 'cdashmm'), 'order_item_type' => 'fee'));
 			if ($item_id) {
 			        wc_add_order_item_meta($item_id, '_line_total', $tax);
 				wc_add_order_item_meta($item_id, '_line_tax', 0);
 				wc_add_order_item_meta($item_id, '_line_subtotal', $tax);
 				wc_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
 				//wc_add_order_item_meta($item_id, '_tax_class', 'zero-rate');
 			 }
      }
	}
    return $order_id;
}

In the function above, the wc_add_order_item() is called for each line item that needs to be created.
For example, if there is a donation field enabled on the front end form, I would like to include the donation amount as a line item in the order.

if($donation){
     $item_id = wc_add_order_item($order_id, array('order_item_name'	=>	__('Donation', 'cdashmm'), 'order_item_type'	=>	'fee'));
     if ($item_id) {
	wc_add_order_item_meta($item_id, '_line_total', $donation);
	wc_add_order_item_meta($item_id, '_line_tax', 0);
	wc_add_order_item_meta($item_id, '_line_subtotal', $donation);
	wc_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
	}
}

So, this creates a line item with the value of donation from the user submitted form. The same is done for Processing Fee and the tax. Here is a screenshot of the WC order on the back end with processing fee and the tax added as items to the order. The donation was disabled on the site. So, it was not added to the order.

Adding line items to WooCommerce order

This enables us to store all the order information in one place and the total now correctly reflects the items in the order.

How I got started with WordPress Plugin Development

 

Almost 2 years ago, when I was planning to learn more about WordPress plugin development and get my hands dirty with some coding, I was given an amazing opportunity.

Morgan Kay who developed the Chamber Dashboard plugins asked me if I would be interested in taking over the development of those plugins. She was taking up a full time job and wouldn’t have time to work on these plugins anymore. I was honored that she considered me. I was very happy for the opportunity, but was also very scared. I hadn’t written a proper plugin before except for some custom scripts for clients.

Though the code was all pretty straightforward, the actual process was new to me. It took me a few months to get on board and get acquainted with the plugins. Continue reading “How I got started with WordPress Plugin Development”

WordPress Widget Gallery Slideshow

WordPress 4.9 was released last week with many new improvements. One of the new features is the ability to add a gallery in the widgets which is a very cool feature. Multiple images can be added at once and the images can be displayed in one or more columns along with the ability to select the size and order of images. This is useful if you want to display flyers for upcoming events or showcase sponsors, award winners etc.

But, the gallery widget also comes with its own limitations like not being able to create a slideshow with the gallery images. Making the gallery images into a slideshow allows you to add more images and not worry about losing space on the sidebar.

The gallery images can be converted into a slideshow/rotating images by adding some simple CSS and JavaScript code. Even if you are not a person who likes to code, don’t worry. This is very easy and simple.

First create your gallery.

  • Go to Appearance -> Widgets.
  • Drag the gallery widget onto the sidebar. Let’s give it a title of ‘Our Sponsors’
  • Then click on ‘Add Images’ and select the images you would like to add to the gallery.
  • Once you select the images, you can organize them in the order you would like.
    • Change the gallery settings if you wish. I set the ‘Link to’ field as none as I do not want to link the image. You can either link it to the attachment page or the media file.
    • Change the number of columns based on how you would like to place your images. Since I selected 4 images in my gallery, I set the columns to 2 so that the images will show up in a nice square. Of course, if we are making the gallery into a slideshow, set the columns to 1.
    • If you select the random order, every time you load your page, the order of the images will change.
    • You can also select the size of the images.
  • Click on ‘Insert Gallery’ to add the images to the widget.
WordPress gallery edit screen
Gallery Edit Screen
  • Click on the ‘Save’ button to display the gallery on your sidebar.

This is how the gallery will look on the front end.

Now it is time to add some code to make the gallery widget into a slideshow. We will be adding some custom CSS and JavaScript code. There are a number of ways to add custom CSS and JS to your WordPress site. You can either use a plugin or add it to your child theme.

Here are some plugins:

Here are some tutorials too if you do not want to use a plugin.

I used the Simple custom CSS and JS plugin to demo the slideshow.

Here is the markup of the gallery:

<section id="media_gallery-3" class="widget widget_media_gallery">

	<h2 class="widget-title">Our Sponsors</h2>

	<div id="gallery-1" class="gallery galleryid-7 gallery-columns-1 gallery-size-thumbnail">
		<figure class="gallery-item active_slide">
			<div class="gallery-icon landscape"><img class="attachment-thumbnail size-thumbnail" sizes="(max-width: 150px) 100vw, 150px" srcset="" alt="" width="150" height="150" /></div>
		</figure>

		<figure class="gallery-item">
			<div class="gallery-icon landscape"><img class="attachment-thumbnail size-thumbnail" sizes="(max-width: 150px) 100vw, 150px" srcset="" alt="" width="150" height="150" /></div>
		</figure>

		<figure class="gallery-item">
			<div class="gallery-icon landscape"><img class="attachment-thumbnail size-thumbnail" sizes="(max-width: 150px) 100vw, 150px" srcset="" alt="" width="150" height="150" /></div>
		</figure>

		<figure class="gallery-item">
			<div class="gallery-icon landscape"><img class="attachment-thumbnail size-thumbnail" sizes="(max-width: 150px) 100vw, 150px" srcset="" alt="" width="150" height="150" /></div>
		</figure>
	</div>

</section>

Since we can add any number of gallery widgets per page or per sidebar, we need to choose exactly which gallery widget we want to convert to the slideshow. For example, I have two gallery widgets in my sidebar, but I only want the first one as a slideshow. So, I will use the widget id to target that particular gallery. Here are a couple of ways to find out the widget id:

Once you have the widget id, you are ready to add the code.

Custom CSS:

#media_gallery-3 figure.gallery-item{
 	position:absolute;
  	display:none;
}
.gallery {
    margin-bottom: 15em;
}
#media_gallery-3 figure.gallery-item.active_slide{
  z-index:99;  
  display:block;
}

JavaScript code:

jQuery(document).ready(function( $ ){
    // Your code in here
   jQuery("#media_gallery-3 .gallery figure.gallery-item").first().addClass("active_slide");
    setInterval( "gcs_gallery_slideshow()", 5000 );
  });

function gcs_gallery_slideshow(){
  //var $next = $('.section.selected').removeClass('selected').next('.section');
  var $next = jQuery("#media_gallery-3 .gallery figure.gallery-item.active_slide").removeClass("active_slide").next(".gallery-item");
if ($next.length) {
    $next.addClass("active_slide"); 
}
else {
    jQuery("#media_gallery-3 figure.gallery-item:first").addClass("active_slide");
}
  //console.log("test");
}

There are a couple of things to remember.

  • Replace #media_gallery-3 with your widget id.
  • The number 5000 in the code is the speed of transition and equals 5 seconds. You can change the number as needed.

You can see a demo of the gallery slideshow here.

Verified by MonsterInsights