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.

US Flag – Using Canvas Element

The canvas tag is a new HTML tag which is used to draw graphics using JavaScript. You can learn more about the canvas tag and its basic usage here. Since it is a relatively new tag, it does not render in all the browsers. For those browsers which do not support the canvas tag,  you would need a fallback image or code inside the canvas tag.

Here is the code to draw the US flag using the canvas tag mostly following the specs for the flag. See the final image.

Open an editor and create a new HTML5 document. You can copy the following code and save it as canvas_demo.html.

Continue reading “US Flag – Using Canvas Element”

Verified by MonsterInsights