How to Create an Embeddable Content Plug-in?

WordPress is a popular platform among content managers as it allows you to share the content with ease. Owing to the numerous functionalities added using plug-in, WordPress is a convenient development and delivery platform. There are many things that you may want to share using WordPress, like a photo gallery, product information etc. Making use of an embeddable content plug-in will help achieve the same.

Sharing Content Across Channels

It is easy to share content across the different channels using RSS feeds, Atom feeds, embeddable widgets etc. While these techniques have their own benefits, they have certain restrictions too! You will see that RSS feeds are limited to sharing posts, while APIs are not really easy to integrate on your websites. The only easy way out is embeddable widgets which in turn relies on JavaScript to embed the specific content to a website.

You can easily create an embeddable widget using which the user can easily insert the content to other websites. Let’s see how a widget code appears before illustrating the technique to create an embeddable content plug-in

<script type=”text/javascript”>

var widget_embed = ‘posts’;

</script>

<script src=”http://www.example.com/widget/wp-widget.js”

type=”text/javascript”>

</script>

<div id=”embed-widget-container”></div>

The crucial element as far as this code is concerned would be wp-widget.js. This function calls the remotely setup WordPress website, gets the content from the website, and embeds it as an iFrame to the website being called.

With this code added to a particular website, you will see that a list of recent posts from the website will be called. This is just an example. The content being called could be anything from an image to a description to a video. For the sake of simplicity, a simple post list will be the content called in

Create the Plug-in

Before you can design an embeddable widget, you will need to create a plug-in. This plug-in will attend to the call for the widget, and return the call by passing on the required data. The em_embed variable will be considered as part of this example, which will be responsible for calling the content from the remote website. The query parameter passed using this function will be intercepted by the plugin and the data will be transmitted out accordingly.

Here, you will calling a post list, and for that purpose you will call for the GET query. The query will be generated using wp-widget.js

Here’s how the plug-in can be generated for this call

<?php

/**

* Plugin Name: WordPress Widget Embed

* Description: Allow people to embed WordPress content in an iframe on other websites

* Version: 1.0

* Author: Sameer Borate

* Author URI: http://www.codediesel.com

*/

class WPWidgetEmbed

{

public function __construct()

{

add_action(‘template_redirect’, array($this, ‘catch_widget_query’));

add_action(‘init’, array($this, ‘widget_add_vars’));

}

/**

* Adds our widget query variable to WordPress $vars

*/

public function widget_add_vars()

{

global $wp;

$wp->add_query_var(’em_embed’);

$wp->add_query_var(’em_domain’);

}

private function export_posts()

{

$outstring = ‘<html>’;

$outstring .= ‘<head><style>’;

$outstring .= ‘ul {

padding:0;

margin:0;

}

li {

list-style-type:none;

}’;

$outstring .= ‘</style></head><body>’;

/* Here we get recent posts for the blog */

$args = array(

‘numberposts’ => 6,

‘offset’ => 0,

‘category’ => 0,

‘orderby’ => ‘post_date’,

‘order’ => ‘DESC’,

‘post_type’ => ‘post’,

‘post_status’ => ‘publish’,

‘suppress_filters’ => true

);

$recent_posts = wp_get_recent_posts($args);

$outstring .= ‘<div class=”widget-posts”><ul>’;

foreach($recent_posts as $recent)

{

$outstring .= ‘<li><a target=”_blank” href=”‘ . get_permalink($recent[“ID”]) . ‘”>’ . $recent[“post_title”]. ‘</a></li>’;

}

$outstring .= ‘</ul></div>’;

$outstring .= ‘</body></html>’;

return $outstring;

}

/**

* Catches our query variable. If it’s there, we’ll stop the

* rest of WordPress from loading and do our thing, whatever

* that may be.

*/

public function catch_widget_query()

{

/* If no ’embed’ parameter found, return */

if(!get_query_var(’em_embed’)) return;

/* ’embed’ variable is set, export any content you like */

if(get_query_var(’em_embed’) == ‘posts’)

{

$data_to_embed = $this->export_posts();

echo $data_to_embed;

}

exit();

}

}

$widget = new WPWidgetEmbed();

?>

If you want your plug-in to intercept the remote call made to your website from other websites, you will need to use the parameters em_embed and em_domain parameters to the query_var variable within the code for the plug-in.

public function widget_add_vars()

{

global $wp;

$wp->add_query_var(’em_embed’);

$wp->add_query_var(’em_domain’);

}

Use the template_redirect hook to accept the query variables. Don’t forget to set the em_embed to global variable

public function catch_widget_query()

{

/* If no ’embed’ parameter found, return */

if(!get_query_var(’em_embed’)) return;

/* ’embed’ variable is set, export any content you like */

if(get_query_var(’em_embed’) == ‘posts’)

{

$data_to_embed = $this->export_posts();

echo $data_to_embed;

}

exit();

}

When you are concerned with post lists, the export_posts function would appear as below

private function export_posts()

{

$outstring = ‘<html>’;

$outstring .= ‘<head><style>’;

$outstring .= ‘ul {

padding-left:10px;

margin:0;

}

li > a {text-decoration: none;

font-family: Arial, Helvetica, Sans-serif;

font-size:12px;

}

li {

border-bottom: 1px solid #c0c0c0;

padding: 3px 0 3px 0;

}

.widget-posts {

width: 250px;

border: 1px solid #c0c0c0;

padding: 12px;

margin-left: 3px;

}’;

$outstring .= ‘</style></head><body>’;

/* Here we get recent posts for the blog */

$args = array(

‘numberposts’ => 6,

‘offset’ => 0,

‘category’ => 0,

‘orderby’ => ‘post_date’,

‘order’ => ‘DESC’,

‘post_type’ => ‘post’,

‘post_status’ => ‘publish’,

‘suppress_filters’ => true

);

$recent_posts = wp_get_recent_posts($args);

$outstring .= ‘<div id=”widget-posts”><ul>’;

foreach($recent_posts as $recent)

{

$outstring .= ‘<li><a target=”_blank” href=”‘ . get_permalink($recent[“ID”]) . ‘”>’ . $recent[“post_title”]. ‘</a></li>’;

}

$outstring .= ‘</ul></div>’;

$outstring .= ‘</body></html>’;

return $outstring;

}

Embeddable Widget Code

Now, you are done with creating the plug-in for the embeddable content. Now, you will need to work on the JavaScript that will help create the embeddable widget. This is the script that will help access the website remotely, call for the content and then share it on the website concerned. Using an iFrame you can easily display the content from another website to your web page.

<script type=”text/javascript”>

var widget_embed = ‘posts’;

</script>

<script src=”http://www.example.com/widget/wp-widget.js”

type=”text/javascript”>

</script>

<div id=”embed-widget-container”></div>

In case, the widget you are creating is set to return a single category of data, then you should ideally use widget_embed variable. Here’s an example of how it would look like

<script src=”http://www.example.com/widget/wp-widget.js”

type=”text/javascript”>

</script>

<div id=”embed-widget-container”></div>

With the wp-widget.js you can call the website remotely and add the content to the iframe. Here is the code for how to use this variable

/**

* wp-widget.js

*

* Inserts an iframe into the DOM and calls the remote embed plugin

* via a get parameter:

* e.g http://www.example.com/?embed=posts

* This is intercepted by the remote ‘WordPress Widget Embed’ plugin

*

*/

(function() {

// Localize jQuery variable

var jQuery;

/* Load jQuery if not present */

if (window.jQuery === undefined || window.jQuery.fn.jquery !== ‘1.7.2’)

{

var script_tag = document.createElement(‘script’);

script_tag.setAttribute(“type”,”text/javascript”);

script_tag.setAttribute(“src”,

“http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”);

if (script_tag.readyState)

{

{

script_tag.onreadystatechange = function ()

{ // For old versions of IE

if (this.readyState == ‘complete’ || this.readyState == ‘loaded’)

{

scriptLoadHandler();

}

};

}

else

{

script_tag.onload = scriptLoadHandler;

}

(document.getElementsByTagName(“head”)[0] || document.documentElement).appendChild(script_tag);

}

else

{

// The jQuery version on the window is the one we want to use

jQuery = window.jQuery;

main();

}

/* Called once jQuery has loaded */

function scriptLoadHandler()

{

jQuery = window.jQuery.noConflict(true);

main();

}

/* Our Start function */

function main()

{

jQuery(document).ready(function($)

{

/* Get ’embed’ parameter from the query */

var widget = window.widget_embed;

var domain = encodeURIComponent(window.document.location);

/* Set ‘height’ and ‘width’ according to the content type */

var iframeContent = ‘<iframe style=”overflow-y: hidden;”

height=”550″ width=”400″ frameborder=”0″

border=”0″ cellspacing=”0″ scrolling=”no”

src=”http://www.example.com/?em_embed=’ + widget + ‘&em_domain=’ + domain + ‘”></iframe>’;

$(“#embed-widget-container”).html(iframeContent);

});

}

With this code and the main() function used within the code, you have inserted the iFrame to your WordPress website. You can change the size of the iFrame depending on your need.

Adding Custom CSS to Content

You can easily add the custom CSS to your plug-in to give it a certain style

private function export_posts()

{

$outstring = ”; $outstring .= ‘

 

‘;

Display Restricted to Particular Domain

Not all domains should ideally display the content that you have created. How is it possible to restrict the call and display of content to certain domains only?

Remember the em_embed variable that you added in the code? With that, it is possible to restrict the display of content to select domain.

Check the domain, and allow the content to be displayed accordingly

Public function catch_widget_query()

{

/* If no ’embed’ parameter found, return */

if(!get_query_var(’em_embed’)) return;

/* ’embed’ variable is set, export any content you like */

if(get_query_var(’em_embed’) == ‘posts’)

{

$allowed_domains = array(‘site1.com’,

‘site2.com’,

‘site3.com’);

$calling_host = parse_url(get_query_var(’em_domain’));

/* Check if the calling domain is in the allowed domains list */

if(in_array($calling_host[‘host’], $allowed_domains))

{

$data_to_embed = $this->export_posts();

echo $data_to_embed;

}

else

{

echo “Domain not registered!”;

}

}

exit();

}

Optimizing Performance

When you use the embeddable widget code, you are actually allowing other websites to remotely access your website using certain plug-ins. This can affect the performance of your website; it can possibly slow down your website. Normally, WordPress websites resort to caching techniques which help deliver the content within the specified time.

In case, you are not using any caching techniques you can use catch_widget_query() function along with WP Transient API code as shown below

public function catch_widget_query()

{

/* If no ’embed’ parameter found, return */

if(!get_query_var(’em_embed’)) return;

/* ’embed’ variable is set, export any content you like */

if(get_query_var(’em_embed’) == ‘posts’)

{

/* Here we are now using the ‘WP Transient API’.

See if we have any saved data for the ‘ewidget’ key.

*/

$cached = get_transient(‘ewidget’);

/* Oops!, the cache is empty */

if(empty($cached))

{
/* Get some fresh data */

$data_to_embed = $this->export_posts();

/* Save it using the ‘WP Transient API’ using the ‘ewidget’ key,

set it to expire after 12 hours.

*/

set_transient(‘ewidget’, $data_to_embed, 60 * 60 * 12);

echo $data_to_embed;

}

/* Yes we found some, so we return that to the user */

else

{

echo $cached;

}

}

exit();

}

Conclusion
Sharing your content across different websites helps you reach out to the audience that concerns you. It is a content marketing strategy that most marketers are utilizing. With this embeddable content plug-in, you can easily share the content, be it images, videos or any other content category, with other websites. Using this code, you know how best to optimize your content sharing efforts while ensuring quick call and sharing. This code also tells you how you restrict some domains from viewing the content being shared.

 

Deepa is a passionate blogger associated with Semaphore Software. A leading Offshore WordPress development company. She loves sharing information regarding WordPress tips & tricks. If you are looking for Hire WordPress Programmers then just get in touch with her.

About deeparanganathan