Categories
JavaScript Plugins Web Development

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.

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

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.

[php]
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
}
[/php]

[php]
$("#loader").css("display", "none");
[/php]

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.

[php]
//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’);
}
[/php]

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.

[php]
function cdash_set_demo_transient(){
set_transient(‘cdash_demo_content_install’, ‘true’);
}
add_action( ‘upgrader_process_complete’, ‘cdash_set_demo_transient’);
[/php]

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.

[php]
$(".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);
},
});
});
[/php]

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.

[php]
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’ );
[/php]

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.

[php]
// 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’,
),
);
[/php]

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

[php]
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 );
[/php]

Then the category for the post needs to be set.

[php]
wp_set_object_terms( $demo_post_id, $bus_demo[‘post_category’], ‘business_category’, $append );
[/php]

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.

[php]
//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 );
[/php]

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

[php]
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;
}
[/php]

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.

Leave a Reply