Sharing the content of your WordPress website is the most efficient way to target users to your web page. Web developers are using different techniques and plugins like RSS Feed, Atom Feed and website APIs for sharing the content of the parent website on different other websites. The main problem while using the RSS and Atom feed is the fact that they can only share the posts on a web page whereas the Website APIs are very tough to integrate with a web page. To get a better and easy way to share the content of the website; the Embeddable widgets were introduced.
Embeddable widgets are the JavaScript codes which are used to show some definite content of a web page on different websites. Google Adsense and Facebook are the most common example of Embeddable widgets which are employed to advertise the services and products on a webpage. Embeddable codes are really easy to install and in this post of mine I will tell you how.
With this tutorial you will be able to develop a widget code to display the recent posts of a parent website on other sub pages.
The Widget Code
Widget Code is the code that authorizes the web page to fetch information from the parent website. This code needs to be inserted in the webpage by the user. The wp-widget.js file is the most important part of this code which connects with the content of the parent website, copy it and paste it onto the page in which the Widget code is pasted.
<script type="text/javascript"> var widget_embed = 'posts'; </script> <script src="https://www.example.com/widget/wp-widget.js" type="text/javascript"> </script> <div id="embed-widget-container"></div>
With this Widget code you will be able to insert the recent post from the website www.example.com. In this code I had provided you the way to fetch posts from the parent website but moreover you can even import pictures, videos, tags, comments, reviews and much more with just a few modifications. The basic algorithm of this code will be the same for these modifications.
Design the Plugin
The first step of designing an embeddable widget is to create a WordPress Plugin which can receive the trigger from the widget code and then reply with the assigned content. I know that this step sounds very tricky and complex but actually it is as much simple as making excuses for coming late.
In the below provided code I am calling the recent posts from the parent website by sending a GET query.
http://www.example.com/?em_embed=posts
The complete code for the plugin is given below.
<?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(); ?>
In the next step we will add the em_embed and em_domain parameter so that the parent website can successfully accept the trigger. In the upcoming stages; this section will also be used to see what kind of data the parent website is sending or the remote website is receiving.
public function widget_add_vars() { global $wp; $wp->add_query_var('em_embed'); $wp->add_query_var('em_domain'); }
Now we are required to attach the query variable with the template_redirect hook so that the processing of data can take place as soon as the em_embed variable is announced with the 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(); }
Here we are going to fetch the list of recent posts from the parent website and hence the export_post function of the code will be abbreviated 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; }
The above stated example can be use4d to export the posts; if you are looking to export some other data then you can use this code as guideline and replace the post code by the code of your desired data type.
Developing the Embeddable Widget Code
Till this stage we are done with creating the WordPress plugin and in the upcoming section we will create the Embeddable Widget Code that can add the triggered content to the calling website or webpage. The most common and hassle free way to display the fetched content on the calling page is to use an iframe. To embed the content into the web page; below is the required code.
<script type="text/javascript"> var widget_embed = 'posts'; </script> <script src="https://www.example.com/widget/wp-widget.js" type="text/javascript"> </script> <div id="embed-widget-container"></div>
If you want to fetch only a single type of data than the widget_embed variable can do the job. The code for the single data type will look like as below.
<script src="https://www.example.com/widget/wp-widget.js" type="text/javascript"> </script> <div id="embed-widget-container"></div>
wp-widget.js is the most important JavaScript that performs all the tasks including, triggering the remote website and embedding the appropriate content to the iFrame. To make it active on your WordPress website, you have to place this wp-widget.js file in any subdirectory of your WordPress website. Below is the code for the wp-widget. js Javascript.
/** * 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="https://www.example.com/?em_embed=' + widget + '&em_domain=' + domain + '"></iframe>'; $("#embed-widget-container").html(iframeContent); }); } })();
Till this step we had successfully integrated the iFrame and content in the DOM via main() function. You can alter the size of iFrame according to your webpage and requirement.
Integrating Custom CSS To The Content
Icing the cake you can also add the Custom CSS to the content displayed on the remote website. to add the Custom CSS, you can use the below provided code.
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>'; . .
You have to different CSS according to the type of fetched content. You can easily pour more beauty to the plugin window with a little more modification. So start exploring your creativity skills to give a unique and elegant look to the plugin window.
Putting a Limit to the Domains
Customizing the domain visibility is possible here; so now you can easily restrict the display to certain domains. As we already have the remote website’s URL in the em_domain variable; we have to simply check the domains and had to choose the content 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(); }
Performance Issues
While allowing the remote websites to fetch the content from your website will surely impose additional load on your server. The situation may get worse when the number of those remote websites is high. So it is always advised to the user that he must carefully allow the remote websites to access the content of the website.
However there are certain methods and Plugins that can help you to fade the affect to an extent. The Plugins like WP Super Cache are really popular among the web developers to store the cache information and hence reducing the server load.
You can even use the WordPress Transient API to use the database as a temporary Cache memory space. After adding the catch_widget_query() to the WordPress API code; the resultant code will look like as follows.
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(); }
I hope that your phobia of creating the Embedded Content plugin for WordPress will be passed after this tutorial post. If you are still finding any hassle then you can share your issues with us in the comments. I will appreciate your feedback and suggestions for my next post.