Tag: WordPress shortcodes

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: , ,

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: , , ,

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 add a posts tags cloud to end of posts

An alternative way of showing related content in your posts is to include a TAG CLOUD at the end of your article. You can create this with an easy shortcode function that will identify the post ID, get the post’s tags and then display the tags as a tag cloud.

Simply add the following shortcode code to your functions.php file, then add the shortcode [dtposts-tagcloud] in your posts where you would like the tag cloud to display.

// add a posts tags cloud to end of posts
function dtposts_tagcloud($echo=false) {
	global $post;
	$tag_ids= wp_get_post_tags($post->ID, array('fields'=>'ids'));
	if($tag_ids) {
		return wp_tag_cloud(array(
			'unit' => 'pt',
			'smallest' => '10',
			'largest' => '22',
			'order' => 'RAND',
			'include' => $tag_ids,
			'echo'=> $echo,
		));
		} }
add_shortcode('dtposts-tagcloud','dtposts_tagcloud');

This uses the standard wp_tag_cloud() function as explained in the WordPress Codex.

This shortcode is demonstrated below. I have added a heading, some css styling, and then called the function using the shortcode. The code is entered as text in the text editor in a WordPress post:

<div style="text-align: center; padding: 20px; background-color: rgba(60,60,60,0.75); margin: 30px;"><b style="color: white; font-size: 18px; font-weight: bold;">POST TAGS</b>
[dtposts-tagcloud]</div>

Here is how it looks:

Check out some more tips and code snippets using the above tags.

Filed under: WordPressTagged with: , , ,

Create shortcode to add custom Twitter support button to your website

mulitple conatct options for businessesAs a business owner, I have learnt that it’s important to offer multiple channels of communication to your clients.

Some people prefer phone calls, others enjoy email, some like to reach out via social media, and then there are those people who would rather visit you in person.

So this is why a “Contact” page on your website or blog, needs to be easily accessible, with all modes of contact, clearly displayed.

[check_list]

  • You want people to communicate with you.
  • You want people to share about you with their social networks.
  • You want people to know that they can reach you in various ways

[/check_list]

All of the above, you probably already realise, in fact it’s probably one of the most obvious requirements for a business website. If you’ve yet to add a contact page to your website, then you better get cracking and set it up as soon as possible, because you’re missing out on business opportunities right now.

[highlight class=”highlight_yellow” style=””]Add something different…[/highlight]

For those of you who already have a “Contact” page, then you probably have social sharing icons, phone details, business address, perhaps a map, and definitely an email form.

Now it’s time to add something that you don’t see on “Contact” pages, at least I haven’t seen this on one yet.

[highlight class=”highlight_yellow” style=””]A clickable button link that encourages people to reach out to you on Twitter, for support and enquiries.[/highlight]

Let me set the scene, so that you can see why I think this might be useful.

A few weeks back, a company that I use for a particular online hosting related service, was having some service issues. I was unable to reach them by phone, email or ticketing system. There were no updates on Social channels or their website. Now I probably could have waited for a response, which eventually would’ve come, however in this day and age, none of us like to wait.

And when my clients started asking me what was going on, I needed an answer as soon as possible.

[highlight class=”highlight_yellow” style=””]So what to do?[/highlight]

Well I decided to reach out to the business through Twitter. I loaded up their webpage in my browser, found my way to their Twitter profile link, clicked on it and ended up on their Twitter page. Next I logged in to Twitter, copied their Twitter name, and pasted it into the “Compose Tweet” and fired off a message to them.

Afterward I was thinking that it would have saved me time and effort, if the website had a button or a link that I could’ve clicked on, which would automatically add their Twitter name and an editable support message into a Tweet.

So this is what I came up with, using the Twitter buttons page https://twitter.com/about/resources/buttons and a little bit of tweaking – an easy to implement shortcode that you can add to your WordPress website, to allow people to reachout to you easily this way.

If you don’t know what a shortcode is, well it’s basically a simple piece of text wrapped up in [ ] square brackets that you add onto a WordPress page or post, that activates a function. http://codex.wordpress.org/Shortcode_API

[highlight class=”highlight_yellow” style=””]How to create your Tweet Support Button:[/highlight]

Ok so let’s first create the function which you add to your childtheme’s functions.php file. And then we’ll attach it to a shortcode and finally add some CSS styling to make it really shine.

Define the function using:

[php]
function dtwd_tweet_support($atts) {
extract(shortcode_atts(array(
‘text’ => ‘I would like help with ‘,
‘related’ => ‘mrdavidtiong’,
‘class’ => ‘twitter-mention-button’,
), $atts));
return ‘<a class="’.$class.’" href="https://twitter.com/intent/tweet?screen_name=mrdavidtiong&text=’.$text.’" data-size="large" data-related="’.$related.’">Contact @MrDavidTiong by Tweet</a>’; ?>
<script type="text/javascript">// <![CDATA[
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
// ]]></script><!–?php }<br ?–>[/php]

What this does is set up a function called “dtwd_tweet_support”, inputs some default actions such as who you are tweeting to, text for entering in the tweet and the styling class of the link. Then it puts it altogether with the Twitter script to generate the Tweet button.

Of course you will want to replace each instance that you see “mrdavidtiong” with your Twitter profile name, so that it works for you.

I chose the default Tweet text as “I would like help with”, but you could change that default to something that suits your situation, such as “Please contact me by” or “I am having trouble with”, or “When will the service be available?” etc.

Note that you can also tailor this Tweet message individually when using the shortcode (as you will see below)

But first let’s add the following to the functions.php file also, insert it at the end of the function code above.

[php]
add_shortcode(‘dtwd-tweet-support’, ‘dtwd_tweet_support’);
[/php]

This code tells our WordPress site that if we use the shortcode [dtwd-tweet-support] anywhere on a page, it needs to activate our function “dtwd_tweet_support” in that spot.

So here’s how you can use this shortcode:

[dtwd-tweet-support] – this will generate a button for people to click on that uses your defaults as defined in the function

[dtwd-tweet-support text=”I really love your service and highly recommend you”] – this will generate a button for people to click on that uses the defaults, but overrides the text default with the text added here in the shortcode

[dtwd-tweet-support text=”I really love your service and highly recommend you” class=”dtwd-tweet-support”] – this will generate a link with the added text, and also style the link with a special class called “dtwd-tweet-support” that will override the default Twitter button styling

Although the default styled button from Twitter is good, you may want to style this to suit your theme, or to suit where you are placing it on the webpage. Using the “dtwd-tweet-support” class, enables you to do this

support tweet button

support tweet

Here is the CSS I used to style the above link, you can modify as you wish, or you can make up your own.

[css]
a.dtwd-tweet-support {
    color: #69BFDC;
    font-family: arial,sans-serif;
    font-weight: bold;
    padding: 10px 0 10px 50px;
text-transform: uppercase;
          }

a.dtwd-tweet-support:before {
    content: " ";
    background: url(‘../theme-name/images/dtwd-tweet-support.png’) no-repeat;
    height: 32px;
    margin: -5px -36px;
    position: absolute;
    width: 32px;

}

a.dtwd-tweet-support:hover {color:red;}

[/css]

Be sure to upload a suitable picture file called “dtwd-tweet-support.png” to use as the icon in the link above. Upload this into your theme’s image folder and adjust the URL, if necessary, for the path to the image, changing “theme-name” to your theme’s name also.

The image size should be 32px. If you’d like some links to some twitter images check out this URL www.iconfinder.com/search/?q=iconset%3Atweetle otherwise the image I used is: www.iconfinder.com/icondetails/82292/128/bird_new_single_twitter_icon

Now that you have added this shortcode function to your website, you can start customising Tweets in your other pages and posts as well. In fact I’m sure there are many creative ways you can implement this on your blog or website.

Try this one out: Contact @MrDavidTiong by Tweet

Be sure to share how you’ve applied this to your site, in the comments below.

Filed under: WordPressTagged with: ,