How To Cache Queries In WordPress

One of the best things about the WordPress CMS is the power of it's built in APIs, there are multiple APIs which make it so easy for you to get and set things in the database. You should never need to edit the database tables, use SQL to insert data in the database or use SQL to get values from the database.

One of the APIs which I find really useful in both plugin and theme development is the Transient API.

What Is Transient API

The transient API is a way of temporary storing data in the WordPress database with an expiry time.

This is mostly used for caching data as you can store data which will only be available for the next 10 minutes or hour. When the expiry time has past then you will not be able to get access to this data.

When storing the data the transient API you will need 3 parameters a key/value pairing and an expiry time. Transient API should always be used to cache data which you expect to expiry.

Set Transients

To set transients you need to use the set_transient() function, as noted above you will need to provide it with 3 parameters.

set_transient( $transient_name, $value, $expiration );
  • $transient_name - Unique ID to be given to the transient.
  • $value - The value to be stored
  • $expiration - The number of seconds to expire.

Get Transients

To get the transients you need to use the get_transient() function and provide it with the transient ID to get the correct value.

get_transient( $transient_name );

If the content of the transient does not exist or has already expired then the return of this function will be false.

When you use transients the value should always be checked to see if it is false because progressing.

if(false === ($data = get_transient($transient_name) ) ){
     // Transient does not exist or has expired and $data must be set
} else {
     // $data has been set and is populated with the contents of the transient
}

Delete Transient

Transients are designed to expiry and delete when the expiry time has past, but you can force the transient to be deleted by using the function delete_transient(). This should be used when an action will mean the data in the transient is no longer valid.

delete_transient( $transient_name );

Putting It All Together

Now that we understand how you can use the different transient functions we can put these together to create a real world example of using Transient to get a list of Twitter updates and set this in a transient for 10 minutes.

$transName = 'list-tweets'; // Name of value in database.
$cacheTime = 10; // Time in minutes between updates.
if(false === ($twitterData = get_transient($transName) ) ){
   //Get new $twitterData
   $json = wp_remote_get("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$num");
   // Get tweets into an array.
   $twitterData = json_decode($json['body'], true);
   set_transient($transName, $twitterData, 60 * $cacheTime);
}
// Use $twitterData

As you can see from this example we first check to see if the transient exists by using the get_transient() function. If this has expired or doesn't exist then this function will return false. If the value of is false then we need to go and populate the $twitterData variable again.

Now we have populated the variable with new data we can then add this to the set_transient() to reset the cache in the transient.

After this if statement we can use the variable $twitterData and know that this will always be the cached data in this variable.

Add Image To Your Plugin On WordPress.org

If you have a look at some of the biggest plugins on the WordPress repository you will see that all of them have a banner image at the top of the page.

Here's an example of some of the other top WordPress plugins.

This is a featured which has only been around and it allows plugin developers to add a custom header image to there plugin on WordPress.org. In this tutorial we are going to investigate how you can add custom header image to your WordPress plugin.

Add Image To Plugin

First you need to create your image, the image needs to be 772px x 250px this is so it will fit perfectly in the space provided on the plugin page.

You don't need to add the title of the plugin as WordPress will overlay the plugin title on the header image.

Now you have an image you need to open up your plugin SVN repository and navigate to the folder where you have the folders branch, truck and tags.

plugin-folder-structure

From this folder create a new folder called assets, this is the folder you can now add multiple images to your plugin. Checkin this folder to your SVN repository.

Add your banner image into this assets folder and name it banner-772x250.png or banner-772x250.jpg, WordPress searches for images of this name to display as the header image.

After this image is checked into the SVN repository your header image will appear at the top of your plugin page the next time the plugins refresh which can be a couple of minutes.

Setup Apple Touch Icon

A device which lots of your visitors will use to access your website are iPhone and iPads. You can't ignore how important it is to allow users of these devices easy access to your site.

There are a few ways you will do this, one of them is responsive design. Use media queries to define how the website looks on these devices.

If you want to start working with media queries on apple devices here is a boilerplate for iPhone and iPad media queries.

Another thing you need to do for the apple devices is to define the apply touch icon in your head tag. This is a tag that defines an icon to use when on web clips. Web clips is a feature on apple devices to to display an icon on the home screen of iOS for the website.

To define the icon to use for the apple-touch-icon is done the same way as you define the favicon.

<link rel="apple-touch-icon" href="apple-touch-icon.png"/>

The default size of the icon should be 57px x 57px.

As some of the devices are different with retina displays you might want to define a different icon for different devices, if so use the following snippet.

<link rel="apple-touch-icon" href="touch-icon-iphone.png" />
<link rel="apple-touch-icon" sizes="72x72" href="touch-icon-ipad.png" />
<link rel="apple-touch-icon" sizes="114x114" href="touch-icon-iphone4.png" />
<link rel="apple-touch-icon" sizes="144x144" href="touch-icon-retina-ipad.png" />

Special Effects

On these icons iOS will add special effects to the icons such as rounded corners, drop shadows and reflected shines. If you don't want iOS to add these effects to the icons then you have to define the icon as precomposed.

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Style Text Like Passwords With CSS

Webkit have lots of experimental CSS properties that you can currently use on your website, one of the properties we are looking at now is the text-security property.

This CSS property allows you to change the the shape of the letter that are displayed in text input boxes.

When the visitor types in a input password text box all the characters they type are converted into shapes to hide the password. But if you don't want to use a password input type then you have to use a text box but then people can see what your typing in.

This is where the -webkit-text-security property comes in you are able to style your textbox to be just like a password input type.

-webkit-text-security: value;
  • circle
  • disc
  • square
  • none

This property currently only exists in webkit browsers so you will only be able to see this in Chrome and Safari browsers.

Recreate Marquee’s With CSS

Back in the early days of the website there was a magically HTML tag which you would see everywhere...this tag is the marquee tag.

This was used on almost every website, if you don't know about this tag or don't remember it, then basically this tag will make any text you add inside it to scroll across the screen. You can variable the speed and direction the text moves across the screen.

Here is a marquee

Many people got annoyed with this tag and thankfully has been deprecated from the html specification.

But someone developing at webkit missed this tag so much they decided to build a webkit CSS property to create a marquee, which can be used as below.

-webkit-marquee: direction increment repetition style speed;

As it is a webkit property it can only be used on chrome or safari browsers.

The marquee property takes 5 parameters:

  • Direction - Defines the direction of the marquee you have the choice of, ahead, auto, backwards, down, forwards, left, reverse, right and up.
  • Increment - Defines the distance the marquee travels per loop.
  • Repetition - This is the number of times it loops around. If you want it to be infinite you can just use the value infinite.
  • Style - This defines the style of the motion on the marquee, alternate, none, scroll, slide.
  • Speed - This defines how fast the marquee will scroll fast, normal, slow

View the demo page to see the different effects created with -webkit-marquee.

.marqueeLeft {
  overflow-x: -webkit-marquee;
  -webkit-marquee: left large infinite slide slow;
  font-size:1.8em;
}
.marqueeAhead {
	overflow-x: -webkit-marquee;
  -webkit-marquee: ahead large infinite slide slow;
  font-size:1.8em;
}
.marqueeAuto {
	overflow-x: -webkit-marquee;
  -webkit-marquee: auto large infinite slide slow;
  font-size:1.8em;
}
.marqueeBackwards {
	overflow-x: -webkit-marquee;
  -webkit-marquee: backwards large infinite slide slow;
  font-size:1.8em;
}
.marqueeDown {
	overflow-x: -webkit-marquee;
  -webkit-marquee: down large infinite slide slow;
  font-size:1.8em;
}
.marqueeForwards {
	overflow-x: -webkit-marquee;
  -webkit-marquee: forwards large infinite slide slow;
  font-size:1.8em;
}
.marqueeReverse {
	overflow-x: -webkit-marquee;
  -webkit-marquee: reverse large infinite slide slow;
  font-size:1.8em;
}
.marqueeRight {
	overflow-x: -webkit-marquee;
  -webkit-marquee: right large infinite slide slow;
  font-size:1.8em;
}
.marqueeUp {
overflow-x: -webkit-marquee;
  -webkit-marquee: up large infinite slide slow;
  font-size:1.8em;
}

Demo

Use CSS To Add Stroke Around Text

With some of the new graphical features you see in CSS3 it can start to add more and more effects to your HTML elements the same way you used to have to use photoshop to do.

Things like box shadow and color gradients are now so easy to do in CSS that you don't even need photoshop anymore. Here is another CSS property that you might not realise existed but it's another effect you would normally do in Photoshop and that's adding a stroke around text, just by using the CSS property text-stroke.

Currently this property is only supported on webkit so it will only work on Chrome or Safari, and you can only use it by prefixing the property with -webkit-.

-webkit-text-stroke: <width>
<color>;

This accepts two values the width of the stroke and the colour of the stroke.

This property now allows you to create a cool outline of any font you are using on your website.

Black Stroke

Black Stroke

.blackandwhite{
	font-family: 'Courgette';
	font-size:3em;
	color: black;
	text-align: center;
        -webkit-text-fill-color: white;
        -webkit-text-stroke: 2px black;
}

Red Stroke

Red Stroke

.redandblack{
	font-family: 'Courgette';
	font-size:3em;
	text-align: center;
	color: red;
        -webkit-text-fill-color: black;
        -webkit-text-stroke: 2px red;
}

Green Stroke

Green Stroke

.greenneon{
	font-family: 'Courgette';
	font-size:3em;
	text-align: center;
	color: green;
        -webkit-text-fill-color: black;
        -webkit-text-stroke: 2px green;
}

As you can see from the above examples is that we have also added another webkit property -webkit-text-fill-color. This property will overwrite the text color with this value. This means that we can set the text color to be something default and this is what the other browsers will see.

Then adding the -webkit-text-fill-color will overwrite the color so we can now use the -webkit-text-stroke to add the webkit stroke.

View the demo to see these affects in different browsers.

Demo

Add Stylesheets To WordPress Correctly

When you are developing WordPress plugin or theme then you will always get to a point where you want to add a stylesheet to the page so you can use the CSS classes on your page.

But there are a few ways of doing this but which one is right?

  • You can add the stylesheet link tag directly on the page using the wp_head action
  • You can add the stylesheet link tag directly to the page anywhere.
  • You can use the wp_enqueue_scripts action to add a handle to the wp_enqueue_style.

Well the correct way and they way you should always add stylesheets to your WordPress site in either your plugin or your theme is to use the wp_enqueue_style function.

Why Should You Use wp_enqueue_style?

Why is this the best solution to adding styles to your WordPress page? This is because of the function wp_enqueue_style, this will handle all of the stylesheets that need to be added to the page and will do it in one place.

wp_enqueue_style( $handle, $src, $deps, $ver, $media );

The first parameter of this function is the handle which you use to name the stylesheet. Naming the stylesheet allows an easy way of not adding the same stylesheet twice on the page.

If you have two plugins that use the same stylesheet and the both use the same wp_enqueue_style handle then WordPress will only add the stylesheet on the page once.

When you add things to wp_enqueue_style it adds your styles to a list of stylesheets it needs to add on the page when it is loaded. If a handle already exists it will not add a new stylesheet to this list.

Another good feature of the wp_enqueue_style function is the 3rd parameter $deps, this is dependencies, if you pass an array of stylesheet handles it means this stylesheet will not be added to the page until all of these handles are added.

Example Of Adding Stylesheet

To use the wp_enqueue_style function it should be added on the wp_enqueue_scripts action.

<?php
    add_action( 'wp_enqueue_scripts', 'safely_add_stylesheet' );
    /**
     * Add stylesheet to the page
     */
    function safely_add_stylesheet() {
        wp_enqueue_style( 'prefix-style', plugins_url('style.css', __FILE__) );
    }
?>

The wp_enqueue_scripts action can be used for both CSS and Javascript files the only difference is that for javascript files you don't use the function wp_enqueue_styles your javascript you will use wp_enqueue_script.

Add Stylesheets In Admin Area

If you want to add your stylesheet in the admin area of WordPress, for example on your theme options page or your plugin admin page, then you need to change slighty this.

There is an action called admin_enqueue_scripts which you should use to add styles in the admin area. Inside this action you can then use the same wp_enqueue_style function to add the stylesheet.

<?php
    add_action( 'admin_enqueue_scripts', 'safely_add_stylesheet_to_admin' );
    /**
     * Add stylesheet to the page
     */
    function safely_add_stylesheet_to_admin() {
        wp_enqueue_style( 'prefix-style', plugins_url('style_admin.css', __FILE__) );
    }
?>

But there is a problem with this, now this stylesheet is added to every page of the admin area. If you only want to style the panels differently on your theme options page then using this method will change it everywhere.

If you only want the stylesheet to be added on certain pages in the admin page you have to add something else to the safely_add_stylesheet_to_admin function.

When you use the admin_enqueue_scripts it passes through a parameter to your called function to let you know what page it's on. From this parameter you can check the page and only add the stylesheet on certain pages.

<?php
    add_action( 'admin_enqueue_scripts', 'safely_add_stylesheet_to_admin' );
    /**
     * Add stylesheet to the page
     */
    function safely_add_stylesheet_to_admin( $page ) {
        if( 'options-general.php' != $page )
        {
             return;
        }
        wp_enqueue_style( 'prefix-style', plugins_url('style_admin.css', __FILE__) );
    }
?>

The above function will only add the stylesheet on the options-general.php page.

Conclusion

That's how stylesheets should be added to both the front-end and admin area of your WordPress site. The benefits and ease of using the wp_enqueue_style is massive that you shouldn't need to add your stylesheets using the wp_head action.

Allow User Editable Content With CSS

On some CMS systems it allows users to directly edit content on the page so that they can preview the change immediately on screen. The way they do this is with Javascript to change any selected paragraph into a textarea and add the paragraph text into this textarea.

But there is a better way you can do this with just CSS, there is a new CSS property which will allow the user to edit the HTML content on-screen.

This property is -user-modify which will change the element to allow the user to edit the content, this is currently only supported on Webkit and Firefox browsers.

Webkit User Modify

-webkit-user-modify: read-only | read-write | read-write-plaintext-only;

This allows for 3 different values:

  • read-only - This is the default and will not allow the user to edit the element
  • read-write - This allows the user to write the content
  • read-write-plaintext-only - User can overwrite the content but only plain text so if you paste anything in here the formatting will be lost.

Moz User Modify

-moz-user-modify: read-only | read-write | write-only

This also allows three values but they are slightly different.

  • read-only - This is the default you can read the content but not write the content.
  • read-write - This allows the user to both read and write the content.
  • write-only - This will just allow the visitor to write then content.

View the demo to see how this will work

Demo

Use In CMS

The way this can be used in a CMS page is for admin user to preview a page of their content on the real page and not in a text editor. Then allow the admin user to click on a paragraph, you can then add the -user-modify CSS property to the clicked element. When this element loses focus you can grab the changed content and use AJAX to update the database with the new content.

Changing Appearance Of Element With CSS

I've recently just found this interesting CSS property that allows you to style any element you want as a browser default element.

Each browser has there own default styling for the standard HTML elements you can find on a page, for example a button in Chrome will look different than a button in Firefox.

With this CSS property you apply this to any HTML element and it will look like the default element in that browser. You can now style that anchor tag link to look exactly like that button, or make a paragraph look like a textbox.

All you have to do is use the CSS property -appearance.

This is currently only supported in webkit and firefox browsers so you need to prefix the property with the browser prefixes.

.lookLikeAButton{
     -webkit-appearance:button;
     -moz-appearance:button;
}
.lookLikeAListbox{
     -webkit-appearance:listbox;
     -moz-appearance:listbox;
}
.lookLikeAListitem{
     -webkit-appearance:listitem;
     -moz-appearance:listitem;
}
.lookLikeASearchfield{
     -webkit-appearance:searchfield;
     -moz-appearance:searchfield;
}
.lookLikeATextarea{
     -webkit-appearance:textarea;
     -moz-appearance:textarea;
}
.lookLikeAMenulist{
     -webkit-appearance:menulist;
     -moz-appearance:menulist;
}

Then you can use these CSS classes in the HTML.

<p class="lookLikeAButton">This is a paragraph
<p class="lookLikeAListbox">This is a paragraph
<p class="lookLikeAListitem">This is a paragraph
<p class="lookLikeASearchfield">This is a paragraph
<p class="lookLikeATextarea">This is a paragraph
<p class="lookLikeAMenulist">This is a paragraph

There different elements you can change the appearance to can be found here.
http://css-infos.net/property/-webkit-appearance

In the demo I change paragraphs to these different elements.

Demo

Disable Text Highlighting With CSS

In a previous article I wrote about how you can change the browser selection colour when you highlight text in your browser.

All you need to do is use a CSS selector class of ::selection and define the style to use on your text when a visitors tries to highlight the test.

But what if you want to do the opposite and want to disable your visitor from highlighting the text all together?

There is an experimental property called user select which will allow you to define new instructions when the visitor tries to highlight your content. This feature can be a good way of making it harder for people to highlight your content and copy it into their own website.

All you have to do is use this CSS property.

.disable_text_highlighting {
-webkit-touch-callout: none;
-webkit-user-select: none; /* Webkit */
-moz-user-select: none;    /* Firefox */
-ms-user-select: none;     /* IE 10  */
/* Currently not supported in Opera but will be soon */
-o-user-select: none;
user-select: none;
}

The values on this property are:

  • Auto - Visitors can select all content in the element.
  • None - Selecting content is disabled.
  • Text - Can only select text content.

Browser Support

This is currently support on webkit, firefox and IE 10. To use the property you need to prefix it with the different browser prefixes but you should also place the non-prefixed version to future proof the property.

View the demo to see what it can do.

Demo