Category: WordPress

Add Nivo Lightbox to WordPress using shortcode function

jQuery lightbox Nivo

A popular jQuery plugin for displaying images, galleries and videos in a lightbox is the Nivo Lightbox. It’s simple to use and responsive which is great for making sure that your photos look great on any device including phones and tablets.

There are some easy to follow instructions on the Dev7Studios website for how to setup, otherwise they also offer a WordPress plugin for purchase.

But if you feel like adding Nivo Lightbox to your WordPress website without using a plugin, you can create a shortcode function and include the required jQuery files following the procedure below. Before you start though, make sure that your theme doesn’t already have a lightbox feature that you can use.

How to add lightbox to your WordPress website

Step 1: Download the files

Download zip file from https://github.com/gilbitron/Nivo-Lightbox

Step 2: Extract files and add to your website

Create a folder called “js” inside of your childtheme folder (if you have followed along in some of my other tutorials you might have already setup this folder). Inside this “js” folder create a new folder called “nivolight”, where you will be adding the required Nivo Lightbox files.

Extract the downloaded zip file. Find the following:

  • “themes” folder
  • “nivo-lightbox.css”
  • “nivo-lightbox.min.js”

and FTP upload them to your “nivolight” folder.

Step 3: Setup options

Create a javascript file to setup the lightbox options and choose the selector for Nivo Lightbox. Inside the file put the following code, and amend as you feel like based on the options available.

/* Nivo Lightbox Scripts */
var nivoeffect = nivolightboxing2.effect;
jQuery(document).ready(function ($) {
    $('a.nivolight').nivoLightbox({
        effect : nivoeffect
    });
});

Save the file as “nivolightboxjs.js” and then FTP upload that file into the “nivolight” folder also.

Notes: the selector ‘a.nivolight’ is to target the <a> links with a class of “nivolight”, and the variable “nivoeffect” is being set to contain a parameter passed from shortcode using wp_localize_script.

Step 4: Create shortcode function

You will need to setup 2 functions, one is for registering the scripts and styles. The second one is for creating the shortcode. Add these functions to your childtheme’s “functions.php” file, or otherwise an mu-plugin file.

function nivolightbox_scripts() {
    wp_register_style('nivolightboxcss',get_stylesheet_directory_uri().'/js/nivolight/nivo-lightbox.css');
    wp_register_style('nivolightboxdefaultcss',get_stylesheet_directory_uri().'/js/nivolight/themes/default/default.css');
    wp_register_script('nivolightbox',get_stylesheet_directory_uri().'/js/nivolight/nivo-lightbox.min.js',array('jquery'),'',true);
    wp_register_script('nivolightboxjs',get_stylesheet_directory_uri().'/js/nivolight/nivolightboxjs.js',array('nivolightbox'),'',true);
}
add_action('wp_enqueue_scripts','nivolightbox_scripts');

function nivolightbox_sc($atts, $content = null){
    $nivolightboxing = shortcode_atts(array(
    'effect' => 'fade',
    'url' => '',
    'thumb' => '',
    'alt' => '',
    'title' => '',
    'type' => '',
    'gallery' => '',
    'text' => ''
    ),$atts);
    wp_enqueue_style('nivolightboxcss');
    wp_enqueue_style('nivolightboxdefaultcss');
    wp_enqueue_script('nivolightbox');
    wp_enqueue_script('nivolightboxjs');
    wp_localize_script('nivolightboxjs','nivolightboxing2',$nivolightboxing);
    $n_effect = esc_attr($nivolightboxing['effect']);
    $n_url = esc_url($nivolightboxing['url']);
    $n_alt = esc_url($nivolightboxing['alt']);
    $n_thumb = esc_url($nivolightboxing['thumb']);
    $n_title = esc_attr($nivolightboxing['title']);
    $n_type = esc_attr($nivolightboxing['type']);
    $n_gallery = esc_attr($nivolightboxing['gallery']);
    $n_text = esc_attr($nivolightboxing['text']);
    if ($n_type === '' && $n_gallery === '') {
        $lightboxoutput = '<a class="nivolight" href="'.$n_url.'" title="'.$n_title.'" ><img src="'.$n_thumb.'" alt="'.$n_alt.'" /></a>';
    } 
    elseif ($n_type === '' && $n_gallery !== '') {
        $lightboxoutput = '<a class="nivolight" href="'.$n_url.'" title="'.$n_title.'" data-lightbox-gallery="'.$n_gallery.'" ><img src="'.$n_thumb.'" alt="'.$n_alt.'" /></a>';
    }
    elseif ($n_type == 'iframe' || $n_type == 'inline') {
        $lightboxoutput = '<a class="nivolight" href="'.$n_url.'" title="'.$n_title.'" data-lightbox-type="'.$n_type.'" >'.$n_text.'</a>';
    }
    else {
        $lightboxoutput = '';   
    }
return $lightboxoutput;
}
add_shortcode('nivobox','nivolightbox_sc');

Notes: the first function registers the scripts and styles, which are only enqueued when the shortcode is included on a page.

Step 5: Using the shortcode

If you simply want to add an image onto your page that will open in the lightbox, then use:

[nivobox url="IMAGE URL" title="TITLE" alt="ALT TEXT" thumb="THUMBNAIL URL"]

Clicking on the thumbnail below shows an example.
[nivobox url=”https://www.davidtiong.com/wp-content/uploads/2015/07/bridge-pic1.jpeg” title=”Scenery with bridge – Single Picture” alt=”bridge scenery” thumb=”https://www.davidtiong.com/wp-content/uploads/2015/07/bridge-pic1-288×192.jpeg”]

If you want to create a gallery of images, then include a classname for eg, “gallery1”:

[nivobox url="IMAGE URL" title="TITLE" alt="ALT TEXT" thumb="THUMBNAIL URL" gallery="gallery1"][nivobox url="IMAGE URL" title="TITLE" alt="ALT TEXT" thumb="THUMBNAIL URL" gallery="gallery1"][nivobox url="IMAGE URL" title="TITLE" alt="ALT TEXT" thumb="THUMBNAIL URL" gallery="gallery1"]

Clicking on a thumbnail below shows this example.
[nivobox url=”https://www.davidtiong.com/wp-content/uploads/2015/07/food-pic1.jpg” title=”A food bowl – 1 of 3″ alt=”Lightbox food bowl” thumb=”https://www.davidtiong.com/wp-content/uploads/2015/07/food-pic1-188×188.jpg” gallery=”gallery1″][nivobox url=”https://www.davidtiong.com/wp-content/uploads/2015/07/tea-brewing.jpg” title=”Tea brewing – 2 of 3″ alt=”Lightbox tea brewing” thumb=”https://www.davidtiong.com/wp-content/uploads/2015/07/tea-brewing-188×188.jpg” gallery=”gallery1″][nivobox url=”https://www.davidtiong.com/wp-content/uploads/2015/07/flowers-pic2.jpg” title=”Flowers – 3 of 3″ alt=”Lightbox flowers” thumb=”https://www.davidtiong.com/wp-content/uploads/2015/07/flowers-pic2-188×188.jpg” gallery=”gallery1″]

If you want to include video(s) in the gallery such as a YouTube or Vimeo URL, then use:

[nivobox url="IMAGE URL" title="TITLE" alt="ALT TEXT" thumb="THUMBNAIL URL" gallery="gallery2"][nivobox url="VIDEO URL" title="TITLE" alt="ALT TEXT" thumb="THUMBNAIL URL" gallery="gallery2"][nivobox url="VIDEO URL" title="TITLE" alt="ALT TEXT" thumb="THUMBNAIL URL" gallery="gallery2"]

Clicking on a thumbnail below shows this example, the first one is an image, the second two are videos.
[nivobox url=”https://www.davidtiong.com/wp-content/uploads/2015/07/food-pic1.jpg” title=”A food bowl – 1 of 3″ alt=”Lightbox food bowl” thumb=”https://www.davidtiong.com/wp-content/uploads/2015/07/food-pic1-188×188.jpg” gallery=”gallery2″][nivobox url=”https://www.youtube.com/watch?v=Sz_xVeHV8LI” title=”GoldCoast Video – 2 of 3″ alt=”GoldCoast video” thumb=”https://www.davidtiong.com/wp-content/uploads/2015/07/screenshot11-188×188.jpg” gallery=”gallery2″][nivobox url=”https://www.youtube.com/watch?v=P_q3BdrFsLI” title=”Singapore Video – 3 of 3″ alt=”Singapore video” thumb=”https://www.davidtiong.com/wp-content/uploads/2015/07/screenshot12-188×188.jpg” gallery=”gallery2″]

If you want to include an iframe to another page, then use:

[nivobox url="WEB PAGE URL" title="TITLE" text="LINK ANCHOR TEXT" type="iframe"]

Clicking on the link below loads a page in the iframe lightbox.

[nivobox url=”http://www.example.com” title=”Iframe on a webpage” text=”This link opens up in an iframe lightbox” type=”iframe”]

If you want to include some inline content, such as content in a hidden div, then use:

[nivobox url="DIV ID" title="TITLE" text="LINK ANCHOR TEXT" type="inline"]

Clicking on the link below loads the hidden div content in the lightbox.

[nivobox url=”#inline-div-lightbox” title=”Shows inline hidden content” text=”This link opens up a hidden div” type=”inline”]

A lightbox can be a great tool when used on a website, especially when it comes to displaying photo galleries. Do you use a lightbox on your website?

Filed under: WordPressTagged with: , ,

How to add estimated reading time to your WordPress posts

how to add Estimated Reading Time to your website

Not everyone will agree with the subheading of this article, but hear me out. How often does a child say “Are we there yet?” when on a driving holiday. How often do we type into Google “How long does it take to fly from point A to point B?”

Or how often do we stand in a queue wondering how much time will pass before it’s our turn. How often do we ask “how long will it take”?

You get the point! No one wants to wait, we live in a society where time is our most limited resource.

So when I see websites like Medium.com that include the estimated time to read an article, I understand why they think that it’s important.

Reason 1: Time Management

We are constantly fighting the hands of the clock. This is why time management ideas are so popular. Possibly the most limiting resource we have is time. We are often on the lookout for ways to save time.

If I only have half hour lunch break, I’m not going to sit down to a banquet. If my bedtime is in an hour, I’m not going to start watching an epic 3 hour movie.

However, if I have 5 minutes to spare before my next appointment, I might decide to read a quick blog post. But how do I know how long it’s going to take me to read?

Well my first instinct would be to scroll to the bottom of the page to see how much content is in the article.

So if I land on a blog post and the estimated reading time is shown to me, then this might be what either makes me decide to keep on reading, or save it for later or immediately bounce off the page.

Reason 2: How deep is the article

This one is definitely subjective, and each person will interpret quantity vs quality differently, but this can be indicative of how informative the post might be. Of course it is up to you to make sure that your posts are good quality, as this is more important than how big a post is.

A technical tutorial might be seen as more extensive if the reading time is higher, so this could appeal to someone looking for more indepth articles. Whereas a quick and easy guide would attract those who want something short and simple to follow.

“Reading time can help a reader draw these conclusions and actually increase time spent on site.”

How to add estimated reading time to your website articles

Well option 1 would be to go down the path of adding a WordPress plugin, a quick search will reveal some options here.

Option 2 could be to count up how many words on your page, estimate how many words you can read in a minute, and then divide by this. Or you could also time yourself reading the article. Then just add it manually to the start of your blog article.

However I prefer something a little more automated (saves time) so here is my preference – option 3. I chose with my website to try out a jQuery script called “Reading Time” by Michael Lynch, which is a lightweight script for estimating reading time and adding it to your website.

It’s a relatively simple procedure to include the script using the WordPress enqueue scripts function, customising the script settings and adding to the pages you want to display “time to read”, and then including a little code in your template where you’d like it to appear.

Step 1: Download the jQuery file readingTime.js from github.com/michael-lynch/reading-time, then FTP upload to your theme folder. To keep your jQuery scripts organised I always recommend adding them into a “js” folder inside your childtheme folder. I added the file into a folder called “readingtime” and then added that into “js” folder.

Step 2: enqueue the script by adding the following PHP function to your childtheme’s functions.php file.

function enqueue_readingtime() {
    wp_enqueue_script(
        'readingtimejs',
         get_stylesheet_directory_uri().'/js/readingTime/readingTime.js',
         array('jquery'),
         '',
         true);
}
add_action('wp_enqueue_scripts','enqueue_readingtime');

Make sure to amend the path to your readingTime.js file, if you uploaded into a different folder location. We include a dependency of “jquery” so the script loads after jQuery, and set to true so that it loads in the footer.

Step 3: setup the script settings.
Here you can customise to suit your preferences. You can choose things like whether you want to include word count, the text displayed before the time shown, the word count, the ids or classes that you will target for displaying the output, and other cool stuff. Read up more about it on the author’s page.

For this blog I decided to only display the reading time only on my posts, and to count the number of words in the main div which has a class of “post-content”. For reading speed “wordsPerMinute” I decided that since my blog is more technical than say a food blog or a travel blog, therefore people will read slower to comprehend so I went with a reading speed of 180 wpm, rather than the default of 270 wpm.

Here is my code below, again you need to add this to your functions.php file. Be sure to modify for your website.

function readingtime_posts() {
    if (is_single() && wp_script_is('readingtimejs','done')) {
        ?><script type="text/javascript">jQuery(document).ready(function($) {
$('.post-content').readingTime({
    readingTimeTarget: '.reading-eta',
    wordCountTarget: '.word-count',
    wordsPerMinute: 180,
    round: true,
    prependTimeString: 'Time to Read: '
});
});</script><?php
}}
add_action('wp_footer','readingtime_posts',100);

Step 4: add some code where you’d like to show your reading time display.
This is the final step in the process and we’ll add some selectors based on our script code above.

<?php if (is_single()) {
    echo '<div style="clear:both;"><span class="reading-eta"></span> (<span class="word-count"></span> Words)</div>';
} ?>

The first span class of “reading-eta” is for the time display, and needs to match “readingTimeTarget” value in the previous code. The second span class of “word-count”, needs to match the value for “wordCountTarget” and is obviously the number of words in your content. Your content will be the div class that you chose for your selector, so in my code above I used “.post-content” but you should choose the div class that your post content is contained in. It could be “.entry-content” or “article” or maybe something else.

So that’s how you do it. Be sure to adjust your reading speed based on your type of content that you write about on your blog.

What do you think? Is this something you’d like to implement on your own website. Do you find it useful on websites like Medium that use reading time estimates?

Filed under: WordPressTagged with: , ,

Is my WordPress responsive website mobile friendly?

mobile ready responsive websites

This is the question I was asking myself a couple of days ago. I have a WordPress responsive website, and I know that it works well on mobile devices. So why would Google’s mobile friendly tester show my website as NOT friendly?

Firstly let’s explore why you need a mobile friendly website.

Google’s upcoming algorithm change

Well according to the Google Webmaster blog in a post titled “Finding more mobile friendly search results“, Google will very soon be making a change to the search results displayed on a mobile device.

From the article:
“Starting April 21, we will be expanding our use of mobile-friendliness as a ranking signal. This change will affect mobile searches in all languages worldwide and will have a significant impact in our search results. Consequently, users will find it easier to get relevant, high quality search results that are optimized for their devices”

The key words here are “… will affect mobile searches … worldwide … will have a significant impact in our search results …”

I think you get the picture that if you want to appear when someone is doing a Google search on a mobile device after 21st April 2015, then you need to be mobile friendly.

How to be mobile friendly

Well the preferred way to be mobile, according to Google is to have just one version of your website that is a Responsive Website Design.

What reasons does Google give for this (source: why responsive design):

easier for people to share a single link to a page on your website, rather than multiple links to the same content

easier for Google to index a single url than a separate desktop and mobile url

only have one page for the webmaster to maintain

saves on load time when redirection is required based on device type

improves Googlebot’s crawling efficiency as only one version of a page to be crawled and indexed so “can indirectly help Google index more of your site’s content and keep it appropriately fresh”

So if you are running a WordPress website, then simply choose a responsive theme. You can also use a mobile plugin that creates a mobile version of your website, however given the reasons listed above you would be better off using a responsive theme. There are plenty to choose from and sometimes the theme you are using may actually have a setting to turn on responsive design, so if you are not sure then check the documentation that comes with your theme, or alternatively contact your theme provider.

How to test if your website is now mobile friendly?

This step is nice and easy, since Google have provided us with a really easy tool to use. Simply visit test here and enter your home page url for Google to test.

Another way to test is by setting up your website with Google Webmaster Tools, and view the “mobile usability” section for any errors that Google has found.

What if I have a responsive website and Google is showing it as “not friendly”?

Well this is what I found out the other day. Even though my website is mobile friendly through testing on a range of mobiles and tablets, Google seems to be of the opinion that it is not.

Why is it so?

So I checked using the Chrome developer tools, and switched on the device mobile emulator to verify that the website was still appearing correctly on mobile devices. Yes that checked out ok.

Then I considered why the mobile testing tool might be showing a different result to Google. Reading on the page I realised that Google is trying to view the website exactly as a typical mobile user might see the page. So that means it needs access to all the stylesheets and javascript, images and other resources that might effect how a page looks.

Then it made sense. Based on the way that used to be recommended for WordPress websites, we use the robots.txt file to help prevent crawling and indexing of content that isn’t relevant for search results. In other words, we simply wanted Google and other search engines to crawl the text content of our websites, not all the other files. So the Googlebot was being blocked from crawling all the stylesheets and javascript, so it cannot therefore see the website exactly how it actually appears on a mobile device.

So even though the website is fully responsive, the reason why Google believes it is not is because the robots.txt file blocks the files that Google now wants to be able to view.

So what to do? Do I simply remove the robots.txt file and allow all crawling of the website? Do I amend the file and stop blocking all the files?

A new robots.txt file for Googlebot

I decided that the reason for blocking certain resources on the website is still relevant at this stage, though in the future this may change again. So the best way to fix the issue with Googlebot is to allow it to crawl the javascript, css, images and other important files. However I still may have some files loaded in my website that I don’t want crawled.

Thankfully we can target Googlebot in our robots.txt using “User-agent: Googlebot”. Also although the directive “Allow” is not recognised across all crawlers (so it shows as an error in robots txt testing tools), Google does actually recognise it, provided that it is “the URL path in of a subdirectory, within a blocked parent directory, that you want to unblock” (source: Webmaster tools help).

This is my revised robots.txt tool with an explanation below:

User-agent: Googlebot
Disallow: /cgi-bin/
Disallow: /wp-admin/
Disallow: /wp-content/plugins/
Allow: /wp-content/plugins/*.css
Allow: /wp-content/plugins/*.js
Disallow: /wp-content/mu-plugins/
Disallow: /wp-content/cache/
Disallow: /wp-content/themes/
Allow: /wp-content/themes/*.css
Allow: /wp-content/themes/*.js
Allow: /wp-content/themes/*.gif
Allow: /wp-content/themes/*.png
Allow: /wp-content/themes/*.jpg
Disallow: /*.php$
Disallow: /*.inc$
Disallow: /*? 

User-agent: *
Disallow: /cgi-bin/
Disallow: /wp-admin/
Disallow: /wp-includes/
Disallow: /wp-content/plugins/
Disallow: /wp-content/mu-plugins/
Disallow: /wp-content/cache/
Disallow: /wp-content/themes/
Disallow: /*.php$
Disallow: /*.js$
Disallow: /*.inc$
Disallow: /*.css$
Disallow: /*?

Sitemap: https://www.davidtiong.com/sitemap.xml

Explanation:

  • Lines 1-17 are for Googlebot
  • Lines 19-31 are for all other bots
  • Line 33 is to inform search engines where my sitemap is located
  • Line 4 blocks the directory “plugins”, but lines 5-6 allow Googlebot to access css and js files in there
  • Line 9 blocks the directory “themes”, but lines 10-14 allow Googlebot to access css, js and image files in there

You can add other allow or disallow rules in there as needed using the same pattern, however remember that your robots.txt file is publicly available so be careful what you put in there, eg: don’t put important pathways in there to hidden files.

Submitting the new robots.txt file to Google and testing

Once you have uploaded your new robots.txt file to your website, you want to do the following:

1. Clear any caches to ensure your new robots.txt file is available

2. Purge any old copy of your robots.txt file from your CDN or Cloudflare if applicable

3. Test your robots.txt file for errors – try tool.motoricerca.info/robots-checker.phtml (remember that the allow directive will show as errors)

4. Tell Google about your new robots.txt file by going into your Google Webmaster Tools account, then navigate to Crawl > Robots.txt tester. Then click on the submit button, then next to 3 ask Google to update – click submit (see images below).

Submit robots.txt to Google

mobile friendly changes to robots.txt

5. Check that css, js and image files are not being blocked by Googlebot anymore by using the Robots.txt tester, view the images below as an example.

robots.txt tester

check Googlebot not blocked


6. Check that your website is now mobile friendly using the mobile friendly tester – www.google.com/webmasters/tools/mobile-friendly/.

7. Keep an eye on your Google webmaster tools account over the next couple of weeks to make sure that no new errors are showing up.

How did you go? If you need to print out this page to refer to, then click the button below.

Print a copy

Are you ready now for April 21?

Filed under: Design, WordPressTagged with: , , ,

3 ways you can protect your email address on WordPress

WordPress antispambot protect email address

Whenever you include your email address online you are asking for spam

An email address is a valuable piece of information. In the right hands it becomes valuable for your business, whether you are networking with other businesses or communicating with customers and clients.

In the wrong hands, your email is soon clogged up with useless spam and rot.

So how do you protect your email address on a WordPress website or blog?

Email spamming is all about grabbing email addresses. Programs known as email harvesters scan the internet for email addresses so they can be added to lists and then targeted with garbage (ie unsolicited email). So if you simply paste your email address on a web page, then you you are just signing up for spam.

So instead you want to make it easy for genuine people to contact you, without any obstacles.

Method 1: Don’t show the email address at all

This one really depends on personal preference. I prefer not to display an email address usually, instead providing a simple and easy contact form on a website. The advantage of this is that you can set required information such as a contact phone number, an email address, perhaps how they found out about you or your business, or other specific information. To prevent spam bots filling in the contact form you can use spam plugins such as Anti-spam or use the honeypot technique (hidden field that only spambots fill in and then the email is rejected).

Another advantage of this is that you can redirect the user to a thank you page, or send a customised auto reply, offer a special, perhaps add them to your email newsletter list (with their permission of course).

The main disadvantage is that they might mis-type their email address, they don’t get to use their preferred email client, they don’t get your email address until/unless you reply email, and also the person might not want to fill in the form.

Method 2: Visual Interpretation

This one works quite well and you are simply showing your email address, but not making it readable to spiderbot harvesters.

Either you show a picture image of your email address, or you add it as text in the form myemail(AT)mywebsite(DOT)com.

This works quite well, though the main problem is that a user has to open up their email client then type the email address in, and this can sometimes be too much effort, or otherwise they could mistype and send the email to the wrong place. Then the client might wonder why you never responded.

Method 3: Encode or obfuscate your email address

If you definitely would prefer to display your email address on your website, so that a client can either copy and paste it into their email client, or even a clickable link that opens up the mail client with the email address ready to go, then you can use the WordPress antispambot() function.

It is really easy to use, and to make it even easier I have created a simple shortcode function below that will either extract the email address from the user profile or allow you to type in the email address to use, encode the email address, then display it as a clickable link for you to use.

//antispam email addresses
function hide_email_addresses_sc($atts, $content = null) {
    $emailaddress_fields = shortcode_atts(array(
        'id' => '',
        'email' => ''
    ),$atts);
    $userid = $emailaddress_fields['id'];
    $e_mail = $emailaddress_fields['email'];
    if ($userid !=='' && $e_mail =='') {
        $emailaddress = get_the_author_meta('user_email',$userid);
        return '<a href="mailto:'.antispambot($emailaddress).'">'.antispambot($emailaddress).'</a>';
    }
    if ($userid =='' && $e_mail !=='') {
        return '<a href="mailto:'.antispambot($e_mail).'">'.antispambot($e_mail).'</a>';
    }
    else {
        return '';
    }
}
add_shortcode('hide_email','hide_email_addresses_sc');

Simply add the above shortcode function to your childtheme’s functions.php file and then you can use the shortcode in either of the following ways:

[hide_email id="1"] // this will allow you to display the clickable encoded email address for a registered user on your site (uses the email address in the user profile with the id= 1)

[hide_email email="email@example.com"] // this will allow you to display a clickable encoded email address for the email address you enter

Other options
For alternatives on preventing spam collection of your email address you can review the WordPress Codex.

How do you prevent harvesters grabbing your email address?

Filed under: WordPressTagged with: , ,

Add a jQuery TimeCircle Countdown Timer to WordPress

add jQuery TimeCircles to WordPress

If you host an event on your website, perhaps run a competition or maybe set a product launch date, then you will need a countdown timer.

One great little countdown timer is jQuery TimeCircles. It lets you set a future date and time, or otherwise you can set the timer based on number of seconds. If you set a date and time, then the countdown will finish at the set date and time. If you set a timer based on seconds, then it will start when the page loads.

What I like about TimeCircles is that it looks great, functions well and is responsive for different size devices (if you are using a responsive WordPress theme). I use this counting timer for my webcast replays, so that members know how long they’ve got to watch after the live webcast.

Here is an example of what it looks like, with the timer set for 120 seconds or 2 minutes, and at the end of the countdown it plays a sound and pops up with a message.

[time-circle data_timer=”120″ timestop=”0″ message=”The countdown has finished now!”]

How to add jQuery TimeCircles to WordPress?

It is really easy to add this to your WordPress website. If you have been following along with previous tutorials then you probably already have an idea what procedure we are going to use.

First you will need to download the necessary script files to upload to your website. Then create a script file for the options, then add a couple of functions to your childtheme’s functions.php file, one to register the necessary scripts and styles ready to enqueue in our shortcode function, and the other to add the shortcode function with some basic attributes.

Step 1: Get the materials
Download zip file from the TimeCircles website and extract the files. Next create a new folder inside your WordPress childtheme’s folder called “js”. You may already have this folder created.

Now create a folder inside this “js” folder and call it “TimeCircles”. This is where we will upload our scripts and styles for TimeCircles. Go ahead and upload TimeCircles.css and TimeCircles.js into this folder.

Step 2: Prepare our settings
Ok now we need to create our script file for our TimeCircle options. Create a file called timecirclescript.js and insert the following javascript into it:

/* script for countdown shortcode */
var timecircleanimation = timecircledata2.time_animation;
var timestop = timecircledata2.timestop;
var timemessage = timecircledata2.message;
jQuery(document).ready(function($) {
    $(".timecircle").TimeCircles({
        animation: timecircleanimation,
        count_past_zero: parseInt(timestop,10)
    }).addListener(function(unit, value, total) {
        if(total === 0) {
            document.getElementById('timerend').play();
            alert(timemessage);
        }
    });
});

Now upload this file also into the TimeCircles folder.
Note: you may notice that I’ve set some variables in the script with values such as “timecircledata2.time_animation”. This data is passed across from the wp_localize_script function that we will use in our shortcode. If you are familiar with passing parameter from a shortcode to javascript, then you will understand this. If not then have a read of the article that talks about this.

Step 3: Create the functions
Now edit your childtheme’s functions.php file and add the following 2 functions:

function scripts_for_countdownclock() {
    wp_register_style('timecirclecss',get_stylesheet_directory_uri().'/js/TimeCircles/TimeCircles.css');
    wp_register_script('timecirclejquery',get_stylesheet_directory_uri().'/js/TimeCircles/TimeCircles.js',array('jquery'),'',true);
    wp_register_script('timecirclescript',get_stylesheet_directory_uri().'/js/TimeCircles/timecirclescript.js',array('timecirclejquery'),'',true);
}
add_action('wp_enqueue_scripts','scripts_for_countdownclock');

function countdown_shortcode($atts, $content = null){
    $timecircledata = shortcode_atts(array(
        'data_date' => '0',
        'data_timer' => '0',
        'time_animation' => 'ticks',
        'timestop' => '0',
        'message' => 'time has ended'
    ),$atts);
    wp_enqueue_style('timecirclecss');
    wp_enqueue_script('timecirclejquery');
    wp_enqueue_script('timecirclescript');
    wp_localize_script('timecirclescript','timecircledata2',$timecircledata);
    $d_date = $timecircledata['data_date'];
    $d_timer = $timecircledata['data_timer'];
    if ($d_timer !=='0') { 
        $countdownoutput = '<div class="timecircle" data-timer="'.$d_timer.'"></div>';
    }
    elseif ($d_date !=='0') {
        $countdownoutput = '<div class="timecircle" data-date="'.$d_date.'"></div>'; 
    }
    else {
        $countdownoutput = '<div class="timecircle" data-timer="3600"></div>';
    }
    return $countdownoutput . '<audio id="timerend" src="LINK TO YOUR AUDIO FILE" preload="auto"></audio>';
}
add_shortcode('time-circle','countdown_shortcode');

The first function above takes care of registering our 2 script files and our css file. Make sure that the path to the files matches where you have uploaded the files.

The second function is our shortcode function that sets the attributes, enqueues the files when the shortcode is on a page, and also includes a handy use of wp_localize_script so that we can access some parameters in our script file.

Make sure to upload an audio sound file for playing at the end of countdown, and add that to the function where it says “LINK TO YOUR AUDIO FILE”.

Step 4: Using the shortcode
Simply add [time-circle data_timer="ADD NUMBER OF SECONDS HERE"]

Optional settings:
data_date="" //must be in the format yyyy-mm-dd hh:mm:ss
data_timer="" //default is 3600 seconds (1 hour)
time_animation="" //default is “ticks”; alternative option is “smooth”
timestop="" //default “0” to stop timer when reaches 0; set to “1” for timer to continue counting upwards from 0
message="" //add a custom message that pops up when timer reaches 0

Important note: do not use both “data_timer” and “data_date” in the same shortcode, only choose one. Only use the shortcode once on a page, otherwise there will be unexpected results for localized data, as the variable name will be the same with different values.

Feel free to customise your TimeCircles even further, by editing the settings script in step 2 above, or by adding extra attributes to the shortcode function.

Filed under: WordPressTagged with: , , ,

Passing Parameters from Shortcode to Javascript

wp_localize_scripts

A WordPress shortcode is used to add extra functionality to your web page. It might be to add a print button onto a page, or perhaps a toggle accordion, Google Map, or even a Retweet button.

As well as outputting something to your web page, a shortcode can also be setup to allow passing parameters to a javascript file, which can be particularly useful if you need your shortcode to be used with a script file, and you want the flexibility to change certain variables depending on usage.

How can a shortcode pass data to a javascript file?

We use a WordPress function known as “wp_localize_script” that “localizes a registered script with data for a JavaScript variable”.

The steps are quite simple:

Step 1:
Register your scripts and styles ready to enqueue on pages that have the shortcode.

function some_scripts() {
     wp_register_style('my_stylecss', path to file);
     wp_register_script('my_script_handle', path to file, array(), '', true);
}
add_action('wp_enqueue_scripts','some_scripts');

Step 2:
Setup a shortcode function and add shortcode attributes to your array variable.

function my_shortcode($atts,$content=null) {
    $my_array_variable = shortcode_atts(array(
         'key1' => '',
         'key2' => ''
    ),$atts);

Step 3:
Then enqueue the scripts and styles in your shortcode, and include “wp_localize_script” on the line following the enqueued script, including the same handle as the enqueued script, a unique object name (eg: my_object_name), and the array variable from step 2.

wp_enqueue_style('my_stylecss');
wp_enqueue_script('my_script_handle');
wp_localize_script('my_script_handle','my_object_name',$my_array_variable);

Step 4:
Now besides accessing your attributes in the shortcode output (as per normal), you can also access the variables in your javascript file by using the unique object name and the attribute key (eg: my_object_name.key1)


/* example javascript file */
var some_variable_value = my_object_name.key1;
jQuery(document).ready(function($) {
     $("div").somefunction({some_variable: some_variable_value});
});

Important note: if passing integers you need to call the JavaScript parseInt() function.

In the next post I’ll demonstrate how to use wp_localize_script in a WordPress shortcode that adds a beautiful timer to your page, using jQuery TimeCircles

Filed under: WordPressTagged with: , , ,

Detecting mobile and tablet browsers in WordPress

Mobile detection in WordPress

Even if you are using a responsive website design, sometimes you still need to tweak your styles or scripts on mobile devices. So is there an easy way to do this on a WordPress website?

Well this might be the solution, a little trick that I came across recently, the WordPress conditional tag – wp_is_mobile(). This tag allows you to determine if a visitor is looking at your website on a mobile device such as a phone or tablet, using detection of the browser user agent string – ($_SERVER['HTTP_USER_AGENT']).

Detection is for iPhone, iPad, Android, Silk, Kindle, Blackberry, Opera Mini and Opera Mobi. If you need to style your pages differently for mobile devices then using the wp_is_mobile() conditional tag along with css media queries enables this.

Also if you feel like adapting the device targeting further you could setup your own function as is explained in this StackExchange article.

Using “wp_is_mobile”

Now how to target the mobile device, well if you only want to add something that happens on mobile devices, you could use the following inside a function that you would add to your functions.php file.

if (wp_is_mobile()) {
	//do something on a mobile device
}

As an example, perhaps you might want to disable the auto-detection of phone numbers on mobile devices, so you would want to add the meta format detection to the header of your page when shown on a mobile browser. The following function is for disabling the automatic detection of phone numbers in modern mobile browser.

function add_to_header_mobile() {
     if (wp_is_mobile()) {
          ?><meta name="format-detection" content="telephone=no"/><?php 
     }
}
add_action('wp_head','add_to_header_mobile');

If you are wondering how to add telephone numbers to a website that have a clickable link, when you have disabled the auto detection, then this link will help.

Adding a unique class for styling on mobile browsers

Another way that you could use the mobile detection would be to add a unique class name to the body class of your pages, that only appears when viewed on the mobile device.

function add_is_mobile_bodyclass($classes) {
	//adds a class of "wp_is_mobile" to the body class of the page
	if (wp_is_mobile()) {
		$classes[] = 'wp_is_mobile';
	}
	return $classes;
}
add_filter('body_class','add_is_mobile_bodyclass');

Then you would use the class name “wp_is_mobile” in your css file to target mobile devices. An example could be that on mobiles you want to change the colour of page titles, so it might look something like this:

.wp_is_mobile h1.pagetitle-title { color: #697FB4; }

And if you have a responsive design theme, then you could use the wp_is_mobile class with your css media queries to target tablets and mobile phones differently.

Using the mobile browser detection in jQuery and Javascript

Having a wp_is_mobile class added to the body classes when displayed on a mobile device, means that you could also use this to detect whether to add a particular javascript or jQuery to the page.

jQuery(document).ready(function($) {
     if ($("body").hasClass("wp_is_mobile")) {
          //do something if mobile device detected
     }
     else {
          //do something else
     }
});

Now you have a new tool at your disposal for making your web pages more mobile friendly. What other tips do you use for optimising your WordPress website for mobile devices?

Filed under: WordPressTagged with: , , ,

Using Defer or Async with scripts in WordPress

Async or Defer loading Enqueued Scripts in WordPress

Loading scripts and stylesheets is an integral part of the page loading for any website. These days we are well aware that web pages contain more interactivity, elements and scripts, accomplishing so much more than the early years when a website was just a simple HTML page (the very first website).

Page Loading Speed is Important

So how do we make sure that despite all the stuff that is going on while a webpage loads, the page still loads fast enough to prevent a viewer from impatiently “bouncing” away to another website. Well in WordPress we are encouraged to enqueue the scripts in the footer and load the stylesheets in the header.

The reason for this so that we want the web page’s visual elements to load first, so people see that the page is rendering. Otherwise a blank loading screen is a big turnoff.

The other important reason for “enqueuing” scripts into the footer is so that scripts can access the DOM page elements, which are often required as some scripts search for selectors on the page such as with jQuery.

How do scripts load normally on a web page?

So what happens as a page loads. Before I dive right in, I’d like to say that I am not an expert on this, so if I get something a little wrong, or a lot wrong, then leave a comment and explain it better for us all.

Ok so when the browser starts to render the page it parses the HTML. When a script is detected, the HTML parsing pauses while the script loads and executes. This means that if you have lots of scripts loading in the header, it holds up the page and so it may look like nothing is happening, and that might mean nothing for the viewer to look at!

Using Async or Defer

If we use the “async” option for loading a script file, then when the page loads, HTML parsing is not interrupted as the scripts are fetched (that is they load while the page continues to load), but once the script has finished loading it executes immediately.

While the script executes, HTML parsing is again stopped. However this still means a better user experience, and so using “async” is good for scripts that don’t depend on HTML elements loading first, or what order other scripts are loaded. So if you are loading a Google+ button then that’s fine to use “async” but if you are loading a slider that relies on jQuery script to have loaded first, then using “async” can cause some script issues.

An alternative, and the way that I prefer to load most of the scripts on a WordPress page, is to use “defer“. When you include “defer” in your enqueued script, then the scripts load at the same time that HTML parsing is happening. Then they wait until the page has finished loading, before executing. This means that the page is loaded first, then the scripts run.

What is also important is that they execute in the order they appeared. So if one script relies on another, such as those scripts that rely on jQuery, then your web page will still work the way you hoped!

This is what a defer script call looks like

 <script src="demo_defer.js" defer></script>

Not all is perfect in the browser world

Ok it’s important to add a warning here. Not always do things go the way they are supposed to. As you probably guessed – some browser versions do not play nice and can be erratic with how they “defer”. Thankfully though most modern browser versions do support “defer” correctly.

But always test yourself on different browsers, and if you notice any issues then inspect the javascript loading to see what is the culprit.

A defer code snippet for enqueued scripts in WordPress

The following function is what I use to add defer to enqueued scripts in WordPress. You will note below that I don’t defer for admin scripts, for jQuery itself, or for Internet Explorer 9.

//to add defer to loading of scripts - use defer to keep loading order
function script_tag_defer($tag, $handle) {
    if (is_admin()){
        return $tag;
    }
    if (strpos($tag, '/wp-includes/js/jquery/jquery')) {
        return $tag;
    }
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 9.') !==false) {
	return $tag;
    }
    else {
        return str_replace(' src',' defer src', $tag);
    }
}
add_filter('script_loader_tag', 'script_tag_defer',10,2);

For more reading please checkout the following resources:
growingwiththeweb.com/2014/02/async-vs-defer-attributes
developers.google.com/speed/docs/insights/BlockingJS

Print a nice copy of this page for reference

Filed under: WordPressTagged with: , , , ,

How to add an Instagram feed to your WordPress website

Add Instagram feed widget to website

Many bloggers use Instagram as part of their social media strategy. If you are looking at ways to share your Instagram photos on your WordPress website, then one option is to use the WordPress embed, which simply requires you to copy the Instagram URL of a photo and paste it on its own line in the WordPress editor.

As an example if I put http://instagram.com/p/yiNjY6JrLI/ onto a line all by itself, then the following photo appears.

Fallen lotus #lotus #watergarden #flowers

A post shared by David Tiong (@mrdavidtiong) on

Alternatively you could use a WordPress plugin to add Instagram photos, or otherwise you can try the jQuery Spectragram jQuery script function to connect your website with your Instagram account and then embed photos onto your pages.

I’ve setup this easy to use script to add my 9 latest photos from Instagram into my footer widget using the technique in this article, but you can use this shortcode in a variety of ways, either adding into your sidebar or on a page. There are options in the shortcode to customise the output, and you can modify your photos further using script options and css.

If you want to be able to setup different looking Instagram feeds on separate pages, then you can customise the script to display your user feed, what’s popular at the moment, or by recently tagged. Only use the shortcode once per page however, so if you have added it to your sidebar or footer, then don’t use it also in a post or page.
NB: If you want to add multiple instances of Instagram photo feed onto a single page, then you can do this without using the shortcode, but instead adding different jQuery selectors to your custom script.

Here is an example of using the medium size images, displaying the latest 4 images all tagged with #WHPpointofview.

[instagridtwo]

If you’d like to view my Instagram footer widget then scroll down to the bottom of the page. Otherwise here is how to setup your own Instagram shortcode.

Quick Overview of Steps

1. Register an application at Instagram.com/developer to receive a client ID
2. Obtain a token for your application to communicate with Instagram
3. Create the shortcode, setup the script options, and upload the files to your website.
4. Test it out and customise with CSS

It might seem a little complicated, but it’s actually pretty easy to use jQuery Spectragram.

Register an Instagram application

This is a necessary step to validate your script so that you can communicate with Instagram. Go to instagram.com/developer, sign in and click the button that says to register an application or register a client.

Fill in your details, I just used a simple application name like “mywebwidget”, enter in my website URL and for the OAuth redirect_uri I just used my website URL again. Next you need to uncheck the box that says “Disable implicit OAuth”. When you save you will receive your CLIENT ID and CLIENT SECRET. You will need this next.

Obtain an Access Token

Copy the URL below into a browser address bar, modify the parts marked in capital letters with the corresponding values.

https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token

So where it says CLIENT-ID replace with your client ID, and where it says REDIRECT-URI replace with your redirect url. (These are the values from the application/client you just setup)

Once you submit the URL with your updated values it will redirect to your website. Take a look at the address bar and you will see attached to the end of your URL something like … /#access_token=123456789123456798ABCABC

The bit after the access_token= is your ACCESS TOKEN and you will need this, so copy it down into a text file and save on your computer.

That’s it for the Instagram application, though if you want to you can go back into your application via Manage Client and re-tick the box “Disable implicit OAuth”.

Set up the files and shortcode

Download the spectragram.js script from github.com/adrianengine/jquery-spectragram. Save it into a folder called “spectragram” inside a “js” folder, located inside the childtheme folder of your WordPress website. (if you don’t have a “js” folder inside the childtheme folder, then add one). So the path should look like /wp-content/themes/your-childtheme/js/spectragram/

Now create a javascript file (save it as spectragramscript.js in the spectragram folder also) to setup the options for Spectragram. Use the code below, but insert your CLIENT ID and ACCESS TOKEN into the corresponding sections.

/*script for spectragram*/
jQuery(document).ready(function($) {
jQuery.fn.spectragram.accessData = {
accessToken: 'add-access-token',
clientID: 'add-client-id'
};
var instamethod = instag.method;
var instaquery = instag.query;
var instamax = instag.max;
var instasize = instag.size;
var instaclass = instag.class;
$('.'+instaclass).spectragram(instamethod,{
query: instaquery,
max: instamax,
size: instasize,
wrapEachWith: '<li></li>'
});
});

Now you want to setup your shortcode function, so the following code is added to your childtheme’s functions.php file. The first part registers the scripts ready for enqueueing. The second part sets up the shortcode with some default values and enqueues the scripts (so only loading on pages that have the shortcode).

function add_spectragram_files() {
wp_register_script('spectragram',get_stylesheet_directory_uri().'/js/spectragram/spectragram.js',array('jquery'),'',true);
wp_register_script('spectragramscript',get_stylesheet_directory_uri().'/js/spectragram/spectragramscript.js',array('spectragram'),'',true);
}
add_action('wp_enqueue_scripts','add_spectragram_files');

function spectragram_shortcode($atts, $content = null){
$spectragramdata = shortcode_atts(array(
'query' => '',
'max' => '9',
'size' => 'small',
'class' => 'instagrid',
'method' => 'getUserFeed'
),$atts);
wp_enqueue_script('spectragram');
wp_enqueue_script('spectragramscript');
wp_localize_script('spectragramscript','instag',$spectragramdata);
$spectra_class = $spectragramdata['class'];
$instagram_spectragram = '<ul class="'.$spectra_class.'"></ul>';
return $instagram_spectragram;
}
add_shortcode('instagrid','spectragram_shortcode');

How to use the shortcode

Simply add [instagrid query="your-Instagram-username"] to your page or sidebar widget. This will add 9 small photos from your Instagram account onto the page. Options in the shortcode:

  • query=”your username | tag name” //default is empty *so this option must always be included. Use a username if setting method as getUserFeed; use a tag name if setting method as getRecentTagged
  • method=”getUserFeed | getRecentTagged” //default is getUserFeed
  • max=”number” //default is 9
  • size=”small | medium | big” //default is small
  • class=”add a classname” //default is instagrid
  • Remember to only use this shortcode once on a page

Ok so now you will need to style your Instagram photo feed. To do this you simply add some CSS to your childtheme’s style.css file. If you noticed above I used list markup for the photos, so the first CSS modification you would do is to remove the bullets and to change the alignment.

.instagrid li {
display:inline-block;
float:left;
list-style:none outside none;
margin:0;
padding:0;
}
ul.instagrid {
display:inline-block;
margin:0 auto;
}

Here are some more CSS notes:

  • If you are inserting into a text widget, you may need to add more specificity using .textwidget css rules
  • If you wish to manually change the size of the images try adding width rules to the .instagrid li css for eg, width:75px;
  • If you wish to control the overall width of the displayed photos, try adding width or max-width css rules
  • If you want to add the shortcode onto different pages and style each one differently, use the class=”ADD CLASS NAME” option in your shortcode, and then add the corresponding CSS rules.

Now you have your very own Instagram photo feed shortcode setup to use the Instagram API. For more information consult their documentation.

Don’t forget to checkout my Instragram grid in the footer below, and click on one of the images to look at it on Instagram.

Follow my blog with Bloglovin

Filed under: Social Media, WordPressTagged with: , , ,

How to Play Audio on Website

HTML5 Audio and MediaElementJs

The simplest way to play audio on any website is to use the HTML5 audio tag. It’s quick and simple and only requires the following HTML code:

<audio src="your-music-file.mp3" controls></audio>

This audio player is native to whichever browser you are using, so will look different in appearance and size on Firefox vs Internet Explorer vs Android Chrome vs IOS iPhone, etc. And if your browser doesn’t support the audio tag then you will not see any player at all and no music will play. The example below uses the default HTML5 audio code above.

Depending on what music format you are using – mp3, m4a, ogg, wav, wma – you will find out that not every browser supports every format. So what you can do is include multiple formats:

<audio controls>
<source src="your-music-file.mp3" type="audio/mpeg"/>
<source src="your-music-file.wav" type="audio/wav"/>
<source src="your-music-file.ogg" type="audio/ogg"/>
</audio>

*Note: You could even support older browsers by using the “object” tag or including a direct link to download the music file.

Besides the “controls” and “src” attribute, you can also add in “autoplay”, “loop” and “preload”. If using “preload” you’ll need to specify a value (none, metadata or auto). So for example if you wanted the music file to autoplay, loop and preload, you would use:

<audio src="your-music-file.mp3" controls loop autoplay preload="auto"></audio>

What about for WordPress websites?

Well all of the above still works, but as of WordPress 3.6 you have another option. WordPress now comes equipped with MediaElementJs files that will load on your page if you use the WordPress audio shortcode [audio] to play your audio file. This produces a nice new audio player, though not a lot of customisation options, but very useful as it looks the same on different browsers and devices, unlike the native HTML5 audio player which appears differently on each browser.

To use the shortcode, you can simply upload the music file to your WordPress media library using the “Add Media” button, then add onto the page selecting the “Embed Media Player” option. This will add the shortcode to the page like this:

[audio mp3="your-music-file.mp3"][/audio]

As noted there is not much in the way of options for this shortcode, however you can use loop=”on”, autoplay=”on” or preload=”none|auto|metadata”. Also you have the option of including different formats like this:

[audio mp3="your-music-file.mp3" ogg="your-music-file.ogg" wav="your-music-file.wav" ][/audio]

To simplify even further, you can simply paste the url to the music file on a line all by itself and WordPress will recognise the audio file and play it in the audio player. This even works with external music files. Note that the music formats supported are ‘mp3’, ‘m4a’, ‘ogg’, ‘wav’, ‘wma’. Here is a screenshot of what the WordPress audio player looks like:

WordPress audio player

Print a nice copy of this page for reference



For further information about using the included WordPress audio player view the WordPress codex page – http://codex.wordpress.org/Audio_Shortcode

Adding MediaElementJs manually

Depending on your needs for your audio player you may wish to setup your own MediaElementJs files, so that you can customise the player further. Note that the following is not necessary in most cases but here is how to do it if you want more control.

Step 1.
Download and extract mediaelement files from http://mediaelementjs.com/

Step 2.
Copy the “build” folder and paste into the “js” folder in your childtheme (setup a new folder if you don’t have one already). Rename the “build” folder as “mediaelement”.

Step 3.
Delete any files you don’t need. The most important ones to keep are flashmediaelement.swf, mediaelement-and-player.min.js and silverlightmediaelement.xap, as well as the css and image files.

Step 4.
Create a file called mediaelementjsplayer-scripts.js, paste the following javascript in, then upload to your “mediaelement” folder.

jQuery(document).ready(function($) {
    //customise settings and target jquery selector
    $('#audio-player').mediaelementplayer({
        features: ['playpause','volume','current','duration'],
        audioVolume: 'vertical',
        audioWidth: 160,
        audioHeight: 30,
        iPadUseNativeControls: false,
        iPhoneUseNativeControls: false, 
        AndroidUseNativeControls: false,
        alwaysShowHours: true
    });
});

Step 5.
Register the scripts and styles ready for enqueue in our new audio shortcode – add this to your childtheme’s functions.php file or your mu-plugin file.

function mediaelementjs_enqueue() {
    wp_register_style('mediaelementjsplayer-css',get_stylesheet_directory_uri().'/js/mediaelement/mediaelementplayer.css');
    wp_register_style('mediaelementjsplayer-skins',get_stylesheet_directory_uri().'/js/mediaelement/mejs-skins.css');
    wp_register_script('mediaelementjsplayer',get_stylesheet_directory_uri().'/js/mediaelement/mediaelement-and-player.min.js',array('jquery'),'',true);
    wp_register_script('mediaelementjsplayer-scripts',get_stylesheet_directory_uri().'/js/mediaelement/mediaelementjsplayer-scripts.js',array('mediaelementjsplayer'),'',true);
}
add_action('wp_enqueue_scripts','mediaelementjs_enqueue');

Step 6.
Now we’ll create our new audio shortcode, add the following php also to your file, just under the enqueue function in step 5 above.

function mediaelementjs_newplayer($atts, $content=null) {
    $audioplayerdata = shortcode_atts(array(
        'music_src'=>'',
        'music_type'=>'mp3',
        'music_preload'=>'metadata',
        'music_loop'=>'',
        'music_autoplay'=>'',
        'music_class'=>''
    ),$atts);
    wp_dequeue_style('wp-mediaelement');
    wp_dequeue_script('wp-mediaelement');
    wp_deregister_style('wp-mediaelement');
    wp_deregister_script('wp-mediaelement');
    wp_enqueue_style('mediaelementjsplayer-css');
    wp_enqueue_style('mediaelementjsplayer-skins');
    wp_enqueue_script('mediaelementjsplayer');
    wp_enqueue_script('mediaelementjsplayer-scripts');
    $m_src=$audioplayerdata['music_src'];
    $m_type=$audioplayerdata['music_type'];
    $m_preload=$audioplayerdata['music_preload'];
    $m_loop=$audioplayerdata['music_loop'];
    $m_autoplay=$audioplayerdata['music_autoplay'];
    $m_class=$audioplayerdata['music_class'];
    return '<div class="playeraudio"><audio class="'.$m_class.'" id="audio-player" src="'.$m_src.'" type="audio/'.$m_type.'" '.$m_autoplay.' '.$m_loop.' preload="'.$m_preload.'">'.$content.'</audio></div>';
}
add_shortcode('my_audio_player','mediaelementjs_newplayer'); 

This shortcode function setups up the new audio player shortcode, adds the required scripts and styles to the page that the shortcode appears on, while also removing the WordPress MediaElementJs files from being added to the page.

Step 7.
Use the new audio player shortcode:

[my_audio_player src=”your-music-file.mp3″]add support here for older browsers if required[/my_audio_player]

Besides the src of your music file, you can also specify other settings such as:

  • music format type using music_type=”wav|ogg|mp3″; the default is “mp3”
  • music preload using music_preload=”none|metadata|auto”; the default is “metadata”
  • music loop using music_loop=”loop”; the default is none
  • music autoplay using music_autoplay=”autoplay”; the default is none, note also that mobile devices prevent autoplay
  • music class using music_class=”mejs-ted|mejs-wmp”; the default is the standard skin

Also you can style the width and position of the player by adding css to your stylesheet.css file. It’s a good idea to make the css width and height match up with the mediaelementjsplayer-scripts.js files settings for audioWidth and audioHeight.

.playeraudio {
     width: 160px;
     height: 30px;
     margin: 20px auto;
}

Here is how the new player looks using the “mejs-ted” class:

[my_audio_player music_loop=”loop” music_class=”mejs-ted” music_src=”https://www.davidtiong.com/wp-content/uploads/2015/02/music-example.mp3″ music_type=”mp3″][/my_audio_player]

Step 8.
For more information about using mediaelement.js and customisation options, visit http://mediaelementjs.com/



Final Thoughts…

It is a good idea to use the WordPress audio shortcode if possible, as this is the simplest and quickest way to add audio onto your webpages. Also because it uses MediaElementJs and is included with WordPress, it will stay up to date as you update your WordPress in the future. However at the moment the customisation options are limited, so you if you need more flexibility then you are welcome to test out the new MediaElementJs player above.

Filed under: Development, WordPressTagged with: , ,