This post comes again from a client request. They were using the Vertical Scroll plugin for WordPress. However, they needed this scrolling box to work on their multilingual site (Chinese & English). But with this plugin, there’s no shortcode, or way to include it in a translatable page. So, I wrote a really quick plugin enhancement. Check it out, hope you find it useful:
2013
Embed Tudou and Youku videos in WordPress
The challenge this morning was to create a way for a client to embed Tudou videos (Chinese equivalent of Youtube) on their WordPress site in a really easy way. There’s nothing really out there for this, so I decided to take 30 minutes and just write my own plugin. It’s really basic, but it does the job. While I was writing it, I figured I’d also include the ability to embed Youku videos as well. It uses iframes, but could easily be modified to use the embed code or whatever. So, download and enjoy! Or just copy the script here and put in your plugins folder!
Usage:
Find the ID of the video by looking in the URL of your video on Tudou or Youku. Then use that ID in the following shortcode on any post or page:
Tudou videos: [vid site="tudou" id="xxxxxx"]
Youku videos: [vid site="youku" id="xxxxxx"]
Download
Download the plugin here: youku-tudou-embed.zip
Source Code
Here’s the source code. Note: this is based on a tutorial on tutsplus.
2013
WP-Cycle with Previous and Next navigation buttons
So I’m not entirely sure the correct method of doing this, so Nathan Rice, if you’re out there, let me know if you want to take this for your own!
WP-Cycle is a great plugin that just simply lets you upload images into a jQuery-based image slider for use in a WordPress page, theme, whatever. What I’ve done is added some functionality to the plugin that adds left/right arrows, as well as adding support for the scrollHorz, which is one of the default options from the original jQuery Cycle plugin. It’s nothing huge, but check out the code below, and if you like it, replace the wp-cycle.php file in the WP-Cycle plugin folder.
And Nathan, thanks for the great code, hope this helps! I’ve added some CSS below line 481, as well as some HTML markup between lines 415 and 432.
2012
Optimize Page Speed (Load Time) in WordPress: An Ongoing Case Study
I was recently working on a project to bring down the page load times for a client’s website. The main functions of the site are to sell a handful of products, as well as bring in traffic for several popular keywords. The site also gets pretty good Adsense revenue, as well as making money from several affiliate links on pages. He has a lot of traffic, but sales and ads don’t reflect what he should be getting for the amount of visitors. I attribute a lot of this to the page load time. Every web marketer under the sun will tell you that faster page loads almost always means better results, whatever it is you’re hoping to achieve. There is no calculated benefit to somebody waiting for your page to load. The risk that they close the tab or click “back” while they are waiting is just too high.
Site Analysis
This website is built in WordPress, has about 400 posts and 11,000 comments (yeah, a lot of comments!). On average the site gets about 5,000-7,000 visits per day, and the page load times (according to Google Analytics) were around 20-25 seconds. Terrible! Tests on GTmetrix and Pingdom (while both slightly lower than Google Analytics) confirmed the page load times were really high (around 19 seconds in many cases). Something needed to be done. My goal was to bring page load times to around the 5-second mark. The client didn’t want to spend much money on optimization, so that was also something to consider.
Step 1: Caching
WP Super Cache is installed on the site, and has a few settings applied to at least serve cached pages to the visitors. This didn’t help much with page load time, but it did mean the server wasn’t quite so busy producing fresh pages every time a visitor landed on the site. Personally I use W3 Total Cache on my site, but I’ve also had good experiences with WP Super Cache. Check out this post on how to correctly setup WP Super Cache.
Step 2: CDN (Content Delivery Network)
The web host of this website is in Malaysia. I had a sneaking suspicion that with all the traffic the site gets, it was putting serious strain on the shared server, and taking unnecessary amounts of time to send files across the Pacific Ocean to the main demographic – the United States. So my first approach was to setup a CDN for the site. With a CDN, your files are copied (no effort required on your part) to the CDN’s servers and distributed to the visitor from the location closest to them. Not only that, but because the servers are faster, closer, and more optimized for distribution, it means all of your files can be loaded at the same time, instead of a typical sequential load. Keep in mind, this applies for CSS files, images, and javascript on your server. The CDN does not claim to cache and deliver files you are referencing from 3rd party sites (ie, Facebook, Google Plus). If you want to try it out, check out MaxCDN. They’re great.
CDN Results
The CDN we chose for this was MaxCDN. For the 1st Terabyte it was $40, and with a coupon code for 25% off it was even cheaper. Setup was quite simple. Once it was setup, back to the page speed tests.
Before the CDN: 75% of “time spent per domain” was on the website. Meaning that for every 10 seconds the page took to load, 7.5 seconds of that time was being spent loading things from the website’s own server.
After the CDN: 6.45% of “time spent per domain” was on the website. So in plain English, this means that since we “outsourced” all of the big files off the server, that for every 10 seconds loading the page, less than a second was spent on the domain’s actual servers. This is huge!
Now, that being said, I didn’t notice a huge drop in page load speed. I was puzzled by this, but still happy with the results of the CDN. At least we narrowed down that now almost no speed was being lost by waiting for the Malaysian servers to respond. On to the next step!
Step 3: Trimming down server requests
The average page on this website had well over 150 server requests. This means every time the page was loaded, the browser had to go grab 150 different files from dozens of different domains. We needed to trim this down. We had already slimmed the site’s own server requests by offloading them to a CDN, but there were a lot left to deal with. A lot of these requests were because of WordPress plugins. We used P3 Plugin Profiler to cut time spent on loading plugins in half! Plugin bloat is one of the leading causes of WordPress heart attacks, don’t let it happen to you!
Step 4: Social
When an average blog post on the site is loaded, it loads the following:
- sidebar – Facebook Like box (with 12 faces showing)
- sidebar – Twitter feed (latest 10 tweets)
- sidebar – Feedburner count
- post – +1 button
- post – Facebook “Like” button
- post – Facebook Like box (with 12 faces showing)
- theme – floating +1 button
- theme – floating Like button
I’m sure I’m missing something, but you can see there are a lot of calls involved there. For Facebook alone the browser was making 48 requests. So Facebook accounted for over 32% of “time spent per domain”. For every 10 seconds spent on the page, 3 seconds were spent downloading stuff from Facebook! Now, one thing we need to think about is value of these things. This site depended heavily on social networks to get the word out about their products and bring in traffic. The Facebook page alone had close to 4,000 Likes, not to mention all the Twitter followers, Feedburner subscribers, and +1′s. So we couldn’t just take all of these items off. We needed to be deliberate and thoughtful when it came to analyzing the value of these social requests. In the end we left most of the social features enabled, but did remove a floating social icon box. That lessened the requests by a few. Can’t hurt!
Step 5: Intense Debate and WordPress commenting
Found it! It turns out that comments actually ended up being one of the biggest strains on the website.
The site was very popular, and received sometimes hundreds of comments per post. In fact on one of the site’s most popular products there were over 500 comments. The comments were great credibility to the site and product, so removing them outright would be a bad move. So instead of removing, we tried a few different things. First, we disabled IntenseDebate and just tried out WordPress’ default comment styling. This proved…pointless. It meant a few less calls to external sources, but in the end it didn’t save any time.
HOWEVER, I discovered something critical during this part of the process. And it has to do with the link between WordPress and IntenseDebate. The IntenseDebate settings were such that when WordPress loads the comments into the page, IntenseDebate takes them and formats and “pages” them (10 per page in this case). What I didn’t realize until I disabled IntenseDebate was that WordPress did not have its own limit set on “comments per page”. AHA!! So, this one product page was literally loading 500 comments, and then IntenseDebate was just reformatting and paging them to show 10 at a time. So I went to Settings > Discussion and set WordPress to split comments into pages with 10 comments per page. Save, refresh, tada! Now WordPress gave only the 10 comments to IntenseDebate that it was looking for. Instant boost in page speed! This may have been the single biggest drag on the system!
Step 6: Comments and Gravatars
A big reason there were so many requests the browser was making was also largely because of the amount of gravatars used in comments. For these tests we disabled gravatars both in IntenseDebate AND in WordPress. And when a gravatar was unavailable we used the “Blank” avatar. I think enabling the gravatars should work ok, as I’ve heard of a few plugins out there that will cache the gravatars on your site. These images would then in turn be cached by the CDN, therefore speeding everything up once again. But that is a test for another time.
Results: Comparing page load time using Pingdom
Here are my stats on the page load times of 3 pages (home page, the most popular post, and a random post) both before and after the above-mentioned changes. Pingdom allows you to compare three different cities (New York, Dallas, and Amsterdam). So the numbers below are averaged from all 3 city results.
HOME
Before: 151 requests 1.13MB 19.9 seconds
After: 135 requests 0.91MB 4.06 seconds
15.8 seconds saved (page loads 79% faster)
POPULAR POST
Before: 196 requests 1.30MB 11.51 seconds
After: 173 requests 0.97MB 4.8 seconds
6.71 seconds saved (page loads 58% faster)
RANDOM POST
Before: 200 requests 1.47MB 9.73 seconds
After: 182 requests 1.1MB 6.58 seconds
3.15 seconds saved (page loads 32% faster)
Google Analytics Page Speed
And finally, according to Google Analytics these changes have netted a 6.09 second sitewide average savings. That means site-wide pages are loading 27.9% faster than before.
So I didn’t necessarily reach my goal of 5 seconds per page, but we got pretty close. And when you factor out all of the non-targeted countries (client mostly wanted US clients), it was an acceptable change.
I’ve seen a lot of blog posts talking about CDNs, server requests, social plugins, etc. They all talk about how you’ll boost your site load speed by incredible amounts. I’m not really sure I buy it. If you’re dealing with a really bland site that has very well performing plugins, this may be true. But web design is messy. Once you hand a site over to a client, they may get their grubby little hands (meant in the most respectful way possible!) all over it and start doing things that seem to be good ideas. So, as I said, analyzing and optimizing your page load time is a sticky process. It takes weeks, months even to get it right. And then go and add some random plugin, and you have to start pieces of it all over again! But personally, it’s a challenge I love.
Have any tips on optimizing WordPress for faster page load time? Let me know, every site is a work in progress!
Side note: read this on how to set your page load sample in Google Analtyics.
2012
Create a custom taxonomy menu in WordPress
I love the tutorial on how to use WordPress as a Knowledge Base on tutsplus.com, however I have made some adjustments to their final section, the kb_sections function that outputs the custom terms. I’ve also severely commented the code to help you understand. I know when I copied the code from their site I just kind of accepted it as is, so hopefully this helps explain each line so you avoid the blindness I accepted at first!
function kb_sections( $sections = array() ) { // by default $sections is an empty array
// tell the function your custom taxonomy name
$taxonomy = 'section';
// set link class (for determing later if the term is a top-level term)
$link_class = '';
/*
* This IF statement checks if the $sections array is empty.
* If it is empty, then populate it with the top-level taxonomy
* values. Then begin an unordered list in which to place the terms
*/
if ( empty( $sections ) ) {
$link_class = 'root'; // set the link class to root on the first iteration
$sections = get_terms( $taxonomy, array(
'parent' => 0, // only return top-level terms
'hide_empty' => 0 // don't return empty terms
) ); // (taxonomy, args)
echo '<ul id="kb-sections" class="unstyled">'; // start our unordered list
}
/*
* Iterate through each item in the $sections array and output
* the term into the list. Then create a sub-menu of each term
* that either creates the next level of terms or runs a query
* that outputs all posts that are tagged with that term
*/
foreach ( $sections as $section ) { // iterate through each taxonomy term in the array
$section_children = get_terms( $taxonomy, array( // get terms of children
'parent' => $section->term_id, // identify children if the parent is in the $sections array
'hide_empty' => 0 // again, hide empties
) );
echo '<li>'; // create a new list item in the unordered list
echo '<span>' . $section->name . '</span>'; // display the taxonomy name
if ( !empty( $section_children ) ) { // if there are children in the array
echo '<ul id="' . $section->slug . '" class="children">'; // create a new nested unordered list with the ID of the parent slug
kb_sections( $section_children ); // call again the kb_sections which looks for sub-sub-menus
}
if ( empty( $section_children ) ) { // however, if there are no children in the array (aka, we've arrived at the final level)
/*
* The following query looks for all posts that are in
* the section (custom taxonomy) for the custom post
* type (knowledgebase). Also, keep in mind, posts_per_page
* must be set to -1 to show all posts. Otherwise it respects
* the default WordPress settings (whatever you've set in Settings > Reading)
*/
$newargs = array( // arguments for the query to populate lowest menu with items
'post_type'=> 'knowledgebase',
'section' => $section->name,
'order' => 'ASC',
'posts_per_page' => -1
);
$my_new_query = new WP_Query( $newargs ); // run query to find all posts using argument above
echo '<ul>'; //create the final unordered list, one that stores links to titles
while ( $my_new_query->have_posts() ) : $my_new_query->the_post(); // start the custom loop
// this must be output in 5 lines, and not all in one, or else errors are thrown.
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>';
endwhile;
wp_reset_postdata();
echo '</ul>';
}
echo "</li>";
}
echo "</ul>";
}
2012
Set your page load sample rate in Google Analytics
I use the Google Analytics for WordPress plugin to add the Google Analytics tracking code to my site. But in order to take advantage of Google’s Page Speed reports in Google Analytics, there’s one setting you should use. It’s called _setSiteSpeedSampleRate.
If you use that plugin, scroll down to where you see Custom Code and paste in the following code snippet:
_gaq.push(['_setSiteSpeedSampleRate', 100]);
The 100 stands for the percentage of pageviews which should count toward the page load sample. If you have a small site, I see no harm in setting this at 100%. However, if you have a large site, Google will automatically limit the sample rate, so there’s no use in putting it above something like 1%. It all depends on the kind of traffic you get.
Important Note: when you paste the code into the custom code box and save the settings, the page will reload and escape the single quotes by adding a backslash. Keep in mind that if you ever update this page again, it will add another backslash. So each time you update the plugin page, remove the backslashes as if you had just pasted the custom code in. I learned this the hard way when I had about 3 hours of “zero” traffic on my site, not realizing it was just causing a small error in the tracking code by having those backslashes.
2012
How I did it – WordPress plugin – “Did you know?”
This will take you through my code for creating a custom plugin in WordPress. This plugin uses a custom post type, a widget, and some CSS. Find the final product at the end of the post!
One of my clients was looking for a way to do quick, random promotions on his WordPress site. He wanted visitors to see his latest post, or tell them about a product they might not know he sells. So, I rolled up my sleeves and decided to create a simple but custom WordPress plugin.
- Plugin name: Did you know?
- Description: Quickly display random facts on your site and point your visitors to posts, affiliate links, or products.
- Download: Did You Know? WordPress Plugin
So, this plugin needed to do a few things:
- Create a custom post type called “Did you know?”, where the user can quickly create a new “Fact”.
- Create a widget that displays a random fact every time the page refreshes
- Add some CSS styling that can be altered if the user desires
Step 1: Create a Custom Post Type
You could code everything up yourself for your custom post type, but why when you can just generate it? I used the WordPress Custom Post Type Generator to create the following:
/*-------------------------------------------------------------------------------------------*/
/* bt_did_you_know Post Type */
/*-------------------------------------------------------------------------------------------*/
class bt_did_you_know {
function bt_did_you_know() {
add_action('init',array($this,'create_post_type'));
}
function create_post_type() {
$labels = array(
'name' => 'Facts',
'singular_name' => 'Fact',
'add_new' => 'Add New Fact',
'all_items' => 'All Facts',
'add_new_item' => 'Add New Fact',
'edit_item' => 'Edit Fact',
'new_item' => 'New Fact',
'view_item' => 'View Fact',
'search_items' => 'Search Facts',
'not_found' => 'No Facts Found',
'not_found_in_trash' => 'No Facts found in trash',
'parent_item_colon' => 'Parent Fact:',
'menu_name' => 'Did you know?'
);
$args = array(
'labels' => $labels,
'description' => "A list of small facts linked to posts, products, or just for static informative text.",
'public' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'menu_position' => 20,
'menu_icon' => null,
'capability_type' => 'post',
'hierarchical' => false,
'supports' => array('title','editor'),
'has_archive' => false,
'rewrite' => array('slug' => 'fact'),
'query_var' => true,
'can_export' => true
);
register_post_type('bt_did_you_know',$args);
}
}
$bt_did_you_know = new bt_did_you_know();
Step 2: Create a widget
Creating the widget was just a tiny bit more complex. Obviously the best place to look for updated documentation on this process is the WordPress Codex. Here’s my widget. Notice at line 18-19 I’ve commented out the ability to use WordPress’ default “title” attribute of the widget. I realize this is not best practice, but I since I knew my client didn’t actually want to customize this at all, I disabled the title by commenting it out, and just put the title in the body of the widget, to be styled with css.
/*-------------------------------------------------------------------------------------------*/
/* "Did you know?" widget */
/*-------------------------------------------------------------------------------------------*/
class bt_random_fact_widget extends WP_Widget {
function bt_random_fact_widget() {
// Instantiate the parent object
parent::__construct( false, 'Did you know? - Random Fact' );
}
function widget( $args, $instance ) {
// Widget output
extract( $args );
$title = apply_filters( 'widget_title', $instance['title'] );
echo $before_widget;
// if ( ! empty( $title ) )
// echo $before_title . $title . $after_title;
$args = array(
'post_type' => 'bt_did_you_know',
'posts_per_page' => 1,
'orderby' => 'rand'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '</pre>
<div class="did-you-know-title">» ' . $title . '</div>
<pre>';
echo '</pre>
<div class="did-you-know">';
the_content();
echo '</div>
<pre>';
endwhile;
echo $after_widget;
}
function update( $new_instance, $old_instance ) {
// Save widget options
$instance = array();
$instance['title'] = strip_tags( $new_instance['title'] );
return $instance;
}
function form( $instance ) {
// Output admin widget options form
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
} else {
$title = __( 'Did you know?', 'text_domain' );
}
?>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><!--?php _e( 'Title:' ); ?--></label>
<input id="<?php echo $this->get_field_id( 'title' ); ?>" class="widefat" type="text" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />
<!--?php <br ?--> }
}
add_action( 'widgets_init', 'myplugin_register_widgets' );
function myplugin_register_widgets() {
register_widget( 'bt_random_fact_widget' );
}
Step 3: Apply CSS to the Widget
The final step was to apply the CSS to the widget. But I only wanted to apply the CSS when the widget was activated. So I used WordPress’ is_active_widget function to queue up the stylesheet.
add_action( 'init', 'check_widget' );
function check_widget() {
if( is_active_widget( false, false, 'bt_random_fact_widget', true ) ) {
wp_register_style( 'enqueue_my_styles', plugins_url('didyouknow.css', __FILE__) );
wp_enqueue_style( 'enqueue_my_styles' );
}
}
Final Product
Download the final product (free of course!): Did You Know? WordPress Plugin
Installation Instructions:
- Go to Plugins > Add New. Click Upload and upload the zip file to your WordPress site.
- Activate the plugin and you’ll see a new post type appear on the left menu bar called Did You Know?
- Add a few new facts (to test it out)
- Go to Appearance > Widgets and drag the Did You Know? – Random Facts widget into your sidebar.
- Go to your home page (or wherever your sidebar appears), and you should see a random fact display every time you refresh the page!
If you installed it, I’d love to hear thoughts, comments, feedback. As I mentioned above, this was a custom job for a client, so if you find use for it, great!

