Category: Web

How to add custom css to WordPress

How to add custom css to WordPress

While managing your WordPress, you may sometimes want to edit the styling of some parts of your post or your site. Moreover, you want to edit the CSS or add custom CSS without modifying the theme’s source code. Let’s look at some ways to do that.

Use JetPack’s Custom CSS Editor

If you already have JetPack by WordPress.com plugin installed, go to your JetPack plugin settings -> Appearance -> Custom CSS -> Configure your Custom CSS settings, click to open the Custom CSS Editor, then append your custom CSS there and click save.

The custom css will be appended to all the pages in your WordPress website.

Use WP Add Custom CSS plugin

WP Add Custom CSS plugin not only lets you add custom CSS to your whole website, but also to any specific posts or pages that you want.

Once the plugin is installed, it will give you an extra edit box in the post editor and page editor to add your custom css.

Add custom CSS to the whole website.
Add custom CSS to specific posts.
Add custom CSS to specific pages.
Add custom CSS to specific custom post types (such as Woocommerce products).

Use Simple Custom CSS and JS plugin

Simple Custom CSS and JS plugin not only lets you add custom CSS, but also custom JavaScript to your website.

At the time this post is written, this plugin hasn’t let us add custom CSS and Javascript to specific pages or posts. However, it let us manage multiple custom CSS and JavaScript without having to put all of them in the same spot as with the plugins mentioned above.

Manage Custom Codes
Add/Edit CSS
Add/Edit Javascript

Final words

These plugins let us modify the CSS without touching the theme’s source code.

Which of these options suits you best? Let me know in the comment! 😀

How to add custom slots to your WordPress theme

How to add custom slots to your WordPress theme

This tutorial will show you how to add custom slots to your WordPress theme so that you can drag and drop widgets to a location that is not yet defined by your theme.

Custom slots… what?

By custom slots I mean the pre-defined locations on your theme where you can drag and drop widgets to make widgets appears on your website. As you can see in the screenshot below, the custom slots are the elements wrapped in the red square.

The official term for custom slots in WordPress is sidebar. In the early days of WordPress, we can only drag widgets to the side columns of the website, hence the term sidebar. Then, as WordPress grows, the original so-called sidebar can be used everywhere on the website: on the top, in the footer, in between posts, etc. However, the name stays unchanged and the WordPress developers still use that term to refer to the custom slots.

In this tutorial, just to clear the confusion, I will use the term custom slots.

And to make this tutorial more understandable, I will use the Hemingway theme.

After this tutorial, I will have an extra slot as below:

The widgets dragged to that new slot will appear on top of the post column of my Hemingway theme.

Step by step tutorial

Open your theme editor

Do add the extra slot to your theme, first you have to open your theme editor.

On your wp-admin side menu, click on Appearance > Editor. Your theme editor will open.

Select the theme you want to edit.

Register your widget slot

Find the code where your theme already register its slots. Normally it would be in the function.php file.

After the you found the code, copy and insert another block of code for your new custom slot.

As you can see in the screenshot, the theme registers its default slots by adding an action to widgets_init.

add_action( 'widgets_init', 'hemingway_sidebar_reg' );

You can also see that I have added my new custom slot to the hemingway_sidebar_reg function (the block of code in red square).

register_sidebar(array(
    'name' => __( 'Content Column Top', 'hemingway' ),
    'id' => 'content-column-top',
    'description' => __( 'Widgets in this area will be shown on top of content column.', 'hemingway' ),
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>',
    'before_widget' => '<div class="widget %2$s"><div class="widget-content">',
    'after_widget' => '</div><div class="clear"></div></div>'
));

The rest of the code in the hemingway_sidebar_reg function is default code that the theme use to register its original slots, which are Footer A, Footer B, Footer C, Sidebar.

Now if you go to your widgets drag and drop screen, the new extra slot should appear there for you to insert widgets.

For the demo purpose, I dragged a Search widget there.

Make the new slot appear on front end

Now that you can config your new slot, let’s move on to displaying it on the front end.

To do this, open the file that render the html where you want the new slot to appear, and make WordPress render whatever dragged to the new slot there using the function:

<?php dynamic_sidebar( 'content-column-top' ); ?>

To better understand this, look at the screenshot from my website

As you can see, I have inserted some code in the red square, telling WordPress to render the new slot content in between two layers of div.

Now if we go to our front end, the new slot content should appear there. However the styling may be a little bit messed up since we have added new elements to the website.

Adding new CSS to your theme

To make the website beautiful again, I added new CSS to the theme’s CSS file to format the new slot.

You can add custom CSS by editing your theme’s CSS file or by using a plugin.

In my case, I edited my theme’s CSS file as below:

Now the new custom slots appears correctly on my front page.

Final words

Adding a new custom slots (sidebars) to your theme may be a little bit different but you get the idea.

Hope this tutorial can help you customize your theme more conveniently.

Have better ideas? Share with me in the comment!

4 ways to make your WordPress server run faster and more resource efficient

4 ways to make your WordPress server run faster and more resource efficient

If you find your WordPress server running slow, before considering a hardware upgrade, try the following tweaks first.

1. Enable caching

If your website doesn’t need to be real-time all the time, you should enable content caching on your WordPress.

You can enable caching just by installing and activating the well-known WP Super Cache plugin.

The default settings should be good enough so after you install the plugin, just go to the Settings page of the WP Super Cache plugin and make sure Caching On is checked.

This plugin caches your pages and posts as html files and serves those files to users instead of calculating and rendering the posts or pages content every time.

If you must clear the cache, you can always go to the plugin’s Content tab to delete any cached page you want or all of the cache with just one click. The new version will be generated and cached after that.

2. Use a CDN

Using a CDN will free your server from serving static files, especially images. Serving these static files uses a lot of CPU power and disk I/O and stresses your server a lot.

Enabling a CDN on WordPress is as easy as one two three and the best part about it is that you can get an unlimited CDN service for FREE as stated in this post.

Applying a CDN for your WordPress not only makes your server run a lot lighter, but also saves you a lot of bandwidth and traffic cost.

Learn how the 3 best free CDN services can speed up your website and optimize cost.

3. Enable gzip

Enabling gzip compression will make each of your web responses smaller by 2 to 3 times, which results in less network I/O and therefore makes your web server run faster.

The cost of compressing the content is a lot less than the cost of transferring the extra bytes, so after the math, your server runs more resource efficient.

To learn more about gzip and how to enable it for your WordPress, check this post.

4. Enable lazy load

If lazy load is enabled for your website, each image in your web content will not load until the user scroll to the part that it is located and it become visible on the user screen. Practically, this saves a lot of requests and responses between your server and the user’s browser.

If you have a WordPress website, you can enable lazy load by installing the Lazy Load plugin.

Lazy load not only makes your website run a lot more resource efficient but also saves you a lot of network I/O and traffic cost as stated in this post.

 

How do you tweak your WordPress server performance? Let me know in the comment!

5 tips to optimize traffic cost of your WordPress website

5 tips to optimize traffic cost of your WordPress website

Introduction

If you host your website on a cloud service, you may find out that your traffic costs even more than the hardware (CPU, RAM, HDD). If that’s the case, check the following tips on how to optimize your traffic cost.

Monitoring your traffic throughput

Before you optimize your traffic, you should have a monitoring tool for your network, so that you know how much traffic was optimized every time you do an experiment.

If you don’t know any traffic monitoring tool yet, try iftop. This tool can show you the real-time traffic throughput for every IP that is connected to your server. iftop is just like the top command in linux, but instead of monitoring the CPU or RAM like the top command, iftop monitors your network.

Install iftop

# fedora or centos
yum install iftop -y

# ubuntu or debian
$ sudo apt-get install iftop

Run iftop

$ sudo iftop -n -B

iftop console

After you run iftop, the iftop screen would appear like below

The first column is the IP of your current machine.

The second column are the IPs of the remote hosts that connect to your server. For each IP, the first row is the traffic that is sent to the remote host (notice the icon =>) and the second row is the traffic that is received from that remote host (hence the icon <=)

The third column is the real-time traffic amount that is sent or received, where the first sub-column is the average bandwidth per second in the last 2 seconds, the second sub-column is the average bandwidth per second in the last 10 seconds, and the third one is the average bandwidth per second in the last 40 seconds. Most of the time, I look at this third column.

Decide what to optimize

Deciding what cost to optimize is often depends on your hosting plan.

Some hosting plans do not charge for traffic. If that’s the case, the network optimizing is more about resource optimizing, where the lower the network traffic, the more requests your server can handle with the same CPU, RAM and network interface.

Some hosting plans do not charge for in going traffic and only charge for out going traffic. For example, Google Cloud only charge for out going traffic, and the rates differ by the destination zone. The cost for traffic between internal IP’s is a lot a lot cheaper than the traffic between external IP’s between zones, or regions, or continents.

By looking at the network traffic between your server and the remote IP’s and the traffic charging plan of your hosting service, you can decide which traffic to optimize first, and what can be left to be optimized later.

Tip #1. Changing to internal IP where possible

If your hosting plan rates are a lot expensive for external traffic than for internal traffic, try changing the external IP’s of your applications to internal IP’s can save you a lot of money.

For example, Google Cloud does not charge for traffic between internal IP’s within the same zone. Therefore, switching your servers to the same zone and configure them to talk to one another using the internal IP’s can save you a lot. Check your redis, memcached, kafka, rabbitmq, mysql or whatever services that can be run internally, make sure their configurations are optimized.

This action can reduce your traffic cost by 3-10 times.

Tip #2. Enable gzip

If you want to know more about gzip, check this post.

By enabling gzip, the traffic sent out will be compressed and therefore you can save a lot of network bandwidth.

This action can reduce your traffic cost by 3-5 times.

Tip #3. Using a free CDN service

If your website has a lot of images, try using a free CDN service to reduce the cost of serving images.

Believe it or not, the free CDN setup will take only 5 minutes and your traffic can be reduced by 5-10 times.

If you have a WordPress website, just install Jetpack plugin by WordPress.com and then turn on it’s Photon feature and your website is now powered with Jetpack’s free CDN service.

If you don’t want to use Jetpack Photon, you can always use CloudFlare or Incapsula CDN services, which are also free without any limitation on bandwidth or anything.

If your website has a lot of visitors in real-time, you can easily test the effects of the CDN by looking at the iftop console when Jetpack Photon is enabled and when it is disabled.

To read more on how to use a free CDN service on your website, click here.

Tip #4. Enable lazyload

When lazyload is enabled, the images on your website won’t be load until they are visible on the browser. Which means the images that stay at the end for your web pages won’t load at first. Then when the user scrolls the web page to where the images are located, the images will be loaded and shown for the user.

If you have a WordPress website, you can enable lazyload by installing the Lazy Load plugin.

Tip #5. Change your hosting service

I don’t know if this should be counted a tip. Anyways, if your current hosting service is charging too much for you traffic, consider changing to another hosting plan or service. Some hosting services do not charge for traffic such as BlueHost, GoDaddy and OVH.

However, even if you switch to a hosting service with free traffic, you can still consider applying the above tips as they can make your website perform better with less hardware resources.

 

How do these tips work for you? Let me know in the comment! 😀

3 best free CDN services to speed up your website and optimize cost

3 best free CDN services to speed up your website and optimize cost

Introduction

If you own a website and your traffic is growing, it’s time to look into using a CDN for your website. Here are 3 best free CDN services that you can use.

Why should I use a CDN

As your website’s traffic grows, your web server may spend a lot of resources serving static files, especially media files like images. Your traffic cost may become a pain in the ass because on an average website, the traffic sent for images is usually 4-10 times the traffic sent for the html, css, and javascript content. On the other hand, CDNs are very good at caching image and optimizing resources for static files serving, as well as choosing the best server in their network to serve the images to the end user (usually the nearest server to the user).

So, it’s time for your server to do what it’s best at, which is generating web contents; and let the CDNs do what they are best at. That also saves you a bunch since you will only have to pay a lot less for your web traffic. Moreover, the setup is unbelievably easy.

1. Jetpack’s Photon

If you have a WordPress website, the fastest and easiest way to give your website the CDN power is to use the Photon feature of Jetpack by WordPress.com plugin.

First, you will have to install and activate the plugin.

The plugin will ask you to login using the WordPress.com account. Don’t worry. Just create a free WordPress.com account and log in.

In the Jetpack settings page, switch to Appearance tab and enable Photon option.

That’s it. Now your images will be served from WordPress.com’s CDN, and that doesn’t cost you a cent.

How Jetpack’s Photon works

Jetpack’s Photon hooks into the rendering process of your web pages and changes your image urls to the ones cached on WordPress.com CDN. Therefore, every time your users open your web pages, they will be downloading cached images from WordPress.com CDN instead of your web server.

Known issues

Jetpack’s Photon use their algorithm to decide the image resolution to be served to the users. In some rare cases, the algorithm doesn’t work so well and the image will be stretched out of the original width and height ratio. For example, if your image size is actually 720×480 but your image’s name is my_image_720x720.jpg, Photon will guess that your image ratio is 720×720 and set the width and height of the img tag to 1:1 ratio, while the cached image is still at 720:480 ratio, which will make the image stretched out of its correct ratio.

Except for that, everything works perfect for me.

If you ask if I would recommend using Jetpack’s Photon CDN, the answer is definitely yes.

2. Cloudflare

Cloudflare offers a free plan with no limit on the bandwidth nor traffic. The free plan is just limited on some advanced functions like DDOS protection or web application firewall, which most of us may not need.

Cloudflare requires you to change the NS records of your domain to their servers, and that’s it. Cloudflare will take care of the rest. You don’t have to do anything else.

How Cloudflare works

After replace your domain’s NS with Cloudflare’s one, all your users will be redirected to Cloudflare servers. When a user request a resource on your website, whether an html page, an image, or anything else, Cloudflare will serve the cached version on their CDN network to the user without accessing your web server. If a cached version does not exist or has expired, Cloudflare will ask your web server for the resource, and then send it to the user as well as cache it on their CDN if that resource is suitable for caching.

I find Cloudflare doesn’t have the image ratio problem like Photon, since Cloudflare doesn’t try to change the html tags, but instead serve the original html content. The CDN works without changing the image url, because Cloudflare has set your domain records to point to their servers by taking advantage of the NS records we set to their name servers earlier.

3. Incapsula

Like Cloudflare, Incapsula offers the same thing. You will have to edit your domain records to point to their servers. However, with Incapsula, you don’t have to change your NS records. You will just have to change the A record and the www record, which may sound somewhat less scary than giving the service full control of our domain like in the case of Cloudflare.

Incapsula works the same way as Cloudflare. It redirects all the requests to its servers and serves the cached version first if available.

Final words

Trying these CDN services does not cost you anything, and on the other hand may save you a lot of traffic costs as well as make your website more scalable. I would recommend that you try at least one of these services. If you don’t like a CDN after using it, you can always disable it and everything will be back to normal. In my case, the CDN saves me 80 percent of my traffic cost, even though my website does not have a lot of images.

 

Did you find this post helpful? What CDN do you use? Tell me in the comment! 😀

How to enable gzip compression for your website

How to enable gzip compression for your website

Most of the time, gzip compression will make your server perform better and more resource efficient. This tutorial will show you how to enable gzip compression for your nginx server.

What is gzip compression

Gzip is a method of compressing files (making them smaller) for faster network transfers. It is also a file format but that’s out of the scope of this post.

Compression allows your web server to provide smaller file sizes which load faster for your website users.

Enabling gzip compression is a standard practice. If you are not using it for some reason, your webpages are likely slower than your competitors.

Enabling gzip also makes your website score better on Search Engines.

How compressed files work on the web

When a request is made by a browser for a page from your site, your webserver returns the smaller compressed file if the browser indicates that it understands the compression. All modern browsers understand and accept compressed files.

How to enable gzip on Apache web server

To enable compression in Apache, add the following code to your config file

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

How to enable gzip on your Nginx web server

To enable compression in Nginx, you will need to add the following code to your config file

gzip on;
gzip_comp_level 2;
gzip_http_version 1.0;
gzip_proxied any;
gzip_min_length 1100;
gzip_buffers 16 8k;
gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript;

# Disable for IE < 6 because there are some known problems
gzip_disable "MSIE [1-6].(?!.*SV1)";

# Add a vary header for downstream proxies to avoid sending cached gzipped files to IE6
gzip_vary on;

As with most other directives, the directives that configure compression can be included in the http context or in a server or location configuration block.

The overall configuration of gzip compression might look like this.

server {
    gzip on;
    gzip_types      text/plain application/xml;
    gzip_proxied    no-cache no-store private expired auth;
    gzip_min_length 1000;
    ...
}

How to enable gzip on your WordPress

If you have a WordPress website and you can’t edit the Apache or Nginx config file, you can still enable gzip using a plugin like WP Super Cache by Automattic.

After installing the plugin, go to its Advanced Settings tab and check on the settings “Compress pages so they’re served more quickly to visitors. (Recommended) to enable gzip compression.

However, keep in mind that this plugin comes with a lot of more features, some of which you may not want. So if you don’t like the extra features, you can just use a more simple plugin like Gzip Ninja Speed Compression or Check and Enable Gzip Compression.

How to check if gzip is successfully enabled and working

Using Firefox to check gzip compression

If you are using Firefox, do the following steps:

  • Open Developer Tools by one of these methods:
    • Menu > Developer > Toggle Tools
    • Ctrl + Shift + I
    • F12
  • Switch to Network Tab in the Developer Tools.
  • Launch the website that you want to check.
  • If gzip is working, the request to html, css, javascript and text files will have the Transferred column smaller than the Size column, where Transferred column displays the size of the compressed content that was transferred, and the Size column shows the size of the original content before compression.

Using Chrome to check gzip compression

If you are using Chrome, do the following:

  • Open Developer Tools by one of these methods:
    • Menu > More tools > Developer Tools
    • Ctrl + Shift + I
    • F12
  • Switch to Network Tab in the Developer Tools.
  • Launch the website that you want to check.
  • Click on the request you want to check (html, css, javascript or text files), the request detail will be displayed.
  • Toggle Response Headers of that request.
  • Check for Content-Encoding: gzip.
  • If gzip is working, the Content-Encoding: gzip will be there.
  • Make sure you check the Response Headers and not the Request Headers.

Frequently Asked Questions

How efficient is gzip?

As you can see in the Firefox Developer Tools Network Tab, the compressed size is normally one third or one fourth the original size. This ratio differs from requests to requests but usually that’s the ratio for html, css, javascript and text files.

Will gzip make my server slower?

OK, that’s a smart question. Since the server has to do the extra work to compress the response, it may need some more CPU power. However, the CPU power that is saved during transferring the response usually makes up for that, not to say that more CPU power is saved. Therefore, at the end of the day, normally your server would be more CPU efficient.

Should I enable gzip for image files (and media files in general)?

Image files are usually already compressed, so gzip compressing the image will not save you a lot of bytes (normally less than 5%), but on the other hand requires a lot of processing resource. Therefore, you shouldn’t enable gzip for your images and should only enable gzip for html, css, javascript and text files.

How to add featured image column to all posts listing page in WordPress

How to add featured image column to all posts listing page in WordPress

If you want to check if any of your post is missing a featured image, the following plugin will add a column to your All posts listing page (wp-admin/edit.php) to show the posts’ featured images for your convenience.

The plugin is  Featured Image Column by Austin Passy. After you install and activate it, your All posts will be added with an extra column showing the featured image of every post.

Do you know that you can also automatically set the featured image for your post using the first image in that post?

What are your favorite WordPress plugins? Share with me in the comment! 😀

WordPress: How to auto set featured image using the first image in post

WordPress: How to auto set featured image using the first image in post

Introduction

If you are a heavy editor in WordPress, you may find out that most of the time, you just set the first image of your post to be the featured image. Here’s a quick and handy way to help you skip the tedious work and save some labor.

Use Easy Add Thumbnail plugin

The easiest way to automate this is to install the Easy Add Thumbnail plugin by Samuel Aguilera.

Just install, activate it and you’re good to go.

Once activated, this plugin will automatically set the post’s featured image to be the first image in your post content if your post doesn’t have a featured image yet.

If you want to select your own featured image, it will leave the featured image untouched and display your selection instead.

How this works

Let’s take a look at the plugin’s code, which is very simple.

if ( function_exists( 'add_theme_support' ) ) {

    add_theme_support( 'post-thumbnails' ); // This should be in your theme. But we add this here because this way we can have featured images before swicth to a theme that supports them.

    function easy_add_thumbnail($post) {

        $already_has_thumb = has_post_thumbnail();
        $post_type = get_post_type( $post->ID );
        $exclude_types = array('');
        $exclude_types = apply_filters( 'eat_exclude_types', $exclude_types );

        // do nothing if the post has already a featured image set
        if ( $already_has_thumb ) {
            return;
        }

        // do the job if the post is not from an excluded type
        if ( ! in_array( $post_type, $exclude_types ) ) {
            // get first attached image
            $attached_image = get_children( "order=ASC&post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );

            if ( $attached_image ) {
                $attachment_values = array_values( $attached_image );
                // add attachment ID
                add_post_meta( $post->ID, '_thumbnail_id', $attachment_values[0]->ID, true );
            }
        }
    }

    // set featured image before post is displayed (for old posts)
    add_action('the_post', 'easy_add_thumbnail');

    // hooks added to set the thumbnail when publishing too
    add_action('new_to_publish', 'easy_add_thumbnail');
    add_action('draft_to_publish', 'easy_add_thumbnail');
    add_action('pending_to_publish', 'easy_add_thumbnail');
    add_action('future_to_publish', 'easy_add_thumbnail');
}

What this code does is that it creates a function called easy_add_thumbnail, which checks if a featured image has been set for your post, and then if a featured image hasn’t been set, it will scan through the images in your post and assign one of them to be the featured image.

Next, this code hooks that easy_add_thumbnail function to the post editing events so that the function will be called every time the post is published or displayed (for old posts).

If you don’t want to install the plugin, you can just add this code snippet to your theme’s function.php file or create your own plugin, whichever you prefer.

Does Easy Add Thumbnail plugin work well with Image Teleporter plugin?

If you don’t know it yet, Image Teleporter plugin helps you upload all the external hosted images in your post to your WordPress hosting and then change the images’ url correspondingly.

Fortunately, Easy Add Thumbnail works well with Image Teleporter. This means that even if the images in your post are hosted externally, when you update or publish your post, the Image Teleporter will first upload them to your hosting and attach the new internally hosted images to your post; then the Easy Add Thumbnail plugin will pick the first among those internal hosted images and set it as the featured image (if you haven’t specified a featured image by that time).

Bonus tip

If you want to check if your posts have featured image or not right in the “All posts” page, try the plugin in this post. Once installed and activated, this plugin adds a column to the posts listing page with the featured image if it exists.

 

Did you find this post helpful?

What are your favorite WordPress tips? Let me know in the comment! 😀

How to add a blank line at the end of the post while editing in WordPress

How to add a blank line at the end of the post while editing in WordPress

This tutorial will show you how to add a blank line at the end of a WordPress post.

During editing in WordPress, sometimes after adding an image (especially an image with a caption) or a “blockquote” at the end of the post, you may find it difficult to add another “normal” line at the end. If you hit ENTER, the editor just add another line of the current image caption or current blockquote, which is definitely not what you want.

If you face the same problem, this simple trick may help you:

  • Switch to Text Editor mode.
  • Scroll to the end of the post in Text Editor mode (you should see your image or your blockquote there
  • Make a new line and type or paste this code at the end of your post (should be after the image or blockquote mentioned above): &nbsp; (including the & in the front and ; at the end)
  • Switch back to Visual Editor mode, you should see a new line as you wanted.

How it works

&nbsp; stands for non-breaking space, a common character entity used in HTML.

Non-breaking Space

A non-breaking space is a space that will not break into a new line.

Two words separated by a non-breaking space will stick together (not break into a new line). This is handy when breaking the words might be disruptive.

Examples:

  • § 10
  • 10 km/h
  • 10 PM

Another common use of the non-breaking space is to prevent that browsers truncate spaces in HTML pages.

If you write 10 spaces in your text, the browser will remove 9 of them. To add real spaces to your text, you can use the &nbsp; character entity.

In our case, &nbsp; tell WordPress to insert a new blank space at the end of the post. And, because &nbsp; stays outside of the previous image or blockquote tag, WordPress takes it into a new line. That’s how the trick works.

Example

For example, if you have a blockquote at the end of your post, when switching to Text Editor, you’ll find something like this

<blockquote>This is the quoted content</blockquote>

Then you after you insert &nbsp; the editor should look something like

<blockquote>This is the quoted content</blockquote>

&nbsp;

Then if you switch back to Visual Editor, a new “normal” line should appear after your blockquote.

 

What are your favorite WordPress tricks? Tell us in the comment! 😀

How to insert a responsive iframe into your WordPress post

How to insert a responsive iframe into your WordPress post

Inserting an iframe to your WordPress post can be somewhat troublesome, but still can be done if you know some tricks. In this post, I’m going to show you how to embed a responsive iframe that can work with your responsive WordPress website beautifully.

To make things more understandable along the post, let’s try to embed the famous slither.io game to our post.

slither.io is a multiplayer game written in HTML5. If you click on their website here, you’ll find out that the game is responsive to most of devices and browsers currently.

Now let’s say we want to put that game into our post as an iframe.

First try

Switch to Text Editor and paste in the iframe linking to the original website.

<iframe src="http://slither.io/"></iframe>

When I switch to Visual Editor, the iframe is there but is very small.

Moreover, the game doesn’t seem to be able to response to the resolution that small and the UI starts to break.

Second try

Switching back to Text Editor, I find out that WordPress has kindly added the width and height for my iframe.

I changed the width and height to 600 and 400 in that order, and the iframe appears better.

<iframe src="http://slither.io/" width="600" height="400"></iframe>

Third try

Now to make the iframe centered in the post, I apply the same trick I used to insert and center a YouTube video in WordPress in a previous post, which adds an extra wrapping div as below.

<div style="text-align: center;">
    <iframe src="http://slither.io/" width="600" height="400"></iframe>
</div>

Everything works perfectly until now.

However, this set-up does not response well every screen resolution. I want it to always takes 100% the width of the parent container. The problem with this is while I can set the width to 100%, I can’t specify the appropriate height of the iframe.

  • If I set the height to a percentage like 50%, I can’t tell the height of the game when it appears, it can be half the screen or it can be larger than the screen, or it can be 0, depending on the parent container.
  • If I set the height to a fixed height like 400px, the iframe won’t response well on some devices, especially mobile devices when the user experience on the portrait mode and landscape mode differ a lot.

The working solution

After some research, I came across this article and ended up with the solution below.

<div style="position: relative; padding-bottom: 56.25%; padding-top: 25px; height: 0;">
    <iframe style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;" 
        src="http://slither.io/" width="100%" height="100%" frameborder="0" 
        scrolling="no" seamless="seamless" allowfullscreen="allowfullscreen">
    </iframe>
</div>

What this code does is that it set the div’s width to 100%, and then make the div’s resolution to always be 16:9 ratio by setting

padding-bottom: 56.25%;

Setting the wrapping div’s position to be relative and the iframe’s position to be absolute also plays an important role here.

Now the div always responses to the parent container and always keeps the resolution ratio at 16:9.

You can change the ratio by changing the "padding-bottom: 56.25%" to the ratio you want (notice that 56.25/100 == 9/16).

If you want to make your code more beautiful, you can add a custom CSS to your site (by altering the theme’s code files or adding a custom Text Widget) as following

.responsiveWrapper {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */
    padding-top: 25px;
    height: 0;
}
.responsiveWrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

And then, just add your iframe like this

<div class="responsiveWrapper">
    <iframe src="http://slither.io/" frameborder="0" 
        scrolling="no" seamless="seamless" allowfullscreen="allowfullscreen">
    </iframe>
</div>

It should work now:

 

Side note. The iframe does not appear on my website because of the mixed content policy, where my website uses https but the iframe source only supports http. Other than that, everything should work fine.

That’s it. Does this solution work for you? Do you have any tips on this? Let me know in the comment! 😀