Using Bit.ly PHP API

Posted on August 15th, 2010 at 8:27 am

URL shortening services became really popular after Twitter went mainstream. The leader in URL shortening services is definitely Bit.ly. In this tutorial i will briefly describe how to use it’s API to autmoatically sorten an URL address.

Signup for Bit.ly API key

Before we can do anything we need to signup for bit.ly api key, you can do it here http://bit.ly/a/sign_up, once you’re done you can find your key at http://bit.ly/a/your_api_key

Hint if you don’t feel like signing up you can use Bit.ly demo api key and password, but keep in mind that it shouldn’t be used in production. Login:bitlyapidemo, ApiKey=R_0da49e0a9118ff35f52f629d2d71bf07

Shortening URL with PHP and Bit.ly

Bit.ly has simple RESTful API so it’s easy to use it, in fact the whole script can be written in just one function.

function bitly_shorten($url)
{
    $query = array(
        "version" => "2.0.1",
        "longUrl" => $url,
        "login" => API_LOGIN, // replace with your login
        "apiKey" => API_KEY // replace with your api key
    );
 
    $query = http_build_query($query);
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://api.bit.ly/shorten?".$query);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 
    $response = curl_exec($ch);
    curl_close($ch);
 
    $response = json_decode($response);
 
    if($response->errorCode == 0 && $response->statusCode == "OK") {
        return $response->results->{$url}->shortUrl;
    } else {
        return null;
    }
}

That’s it just copy and paste this code into your project.

Adding custom buttons to WordPress tinyMCE

Posted on August 15th, 2010 at 7:37 am

Once in a while it might happen that you will need to add custom button to the default tinyMCE editor bundled with WordPress to enchance it’s functionality. Fortunately, WordPress have apprioprate hooks that allow to do this task with ease.

If you do not have time to read the whole article scroll down to the bottom and download completed plugin.

Before we start

In this tutorial i will assume you know the basics about creating WordPress plugins. If not then please read some intruductionary article before going further.

The plugin we are going to create will have a code name TinyPlugin, let’s put it in tiny-plugin directory (inside wp-content/plugins directory). In the main plugin file we are going to use two filters only.

Adding WordPress tinyMCE filters

add_filter('mce_external_plugins', "tinyplugin_register");
add_filter('mce_buttons', 'tinyplugin_add_button', 0);

The first one (mce_external_plugins) register the tinyMCE plugin, second (mce_buttons) is responsible for adding a button tinyMCE tooltip. The callbacks are as follow.

function tinyplugin_add_button($buttons)
{
    array_push($buttons, "separator", "tinyplugin");
    return $buttons;
}
 
function tinyplugin_register($plugin_array)
{
    $url = trim(get_bloginfo('url'), "/";
    $url.= "/wp-content/plugins/tiny-plugin/editor_plugin.js";
 
    $plugin_array["tinyplugin"] = $url;
    return $plugin_array;
}

The tinyplugin_add_button() function adds “separator” and “tinyplugin” to the buttons array. Actually separator is not required, it is just used to separate default buttons from our custom one, on the other hand “tinyplugin” is the name of our plugin which we are going to create in JavaScript.

While tinyplugin_add_button() adds button to the toolbar, it’s tinyplugin_register() function that actually registers the plugin. Now we need to create editor_plugin.js JavaScript that will contain tinyMCE plugin code.

Creating tinyMCE plugin

From the tinyplugin_register() function you might already guessed that we need to create editor_plugin.js file in tiny-plugin directory.

Create it and add to it:

function tiny_plugin() {
    return "[tiny-plugin]";
}
 
(function() {
    tinymce.create('tinymce.plugins.tinyplugin', {
 
        init : function(ed, url){
            ed.addButton('tinyplugin', {
            title : 'Insert TinyPlugin',
                onclick : function() {
                    ed.execCommand(
                    'mceInsertContent',
                    false,
                    tiny_plugin()
                    );
                },
                image: url + "/wand.png"
            });
        }
    });
 
    tinymce.PluginManager.add('tinyplugin', tinymce.plugins.tinyplugin);
 
})();

This code snippet also has two functions (one named and one anonymous). tiny_plugin() function returns content that will be inserted into post after clicking the button. Second anonymous function registers plugin with tinyMCE.

Download tiny-plugin now!

Twitter, PHP oAuth: update status

Posted on June 7th, 2010 at 9:15 pm

Recently Twitter announced they are going disable basic authentication mechanism. Basic auth can be used until June 30th 2010, so there is only less then one month left (assuming you are reading this on June 2010). I admit that for a long time i neglected the OAuth Twitter authorization, it seemed complicated and time consuming in comparison basic auth.

However, when i found out they are shutting down the basic api, i had no other choice then to learn how it works. What it turned out is that with the right tools it’s pretty easy to do. Especially if you are (like me) looking to setup application that will be using only single user. For example to automatically update your status. Read the rest of this entry »

Disable WordPress profile edition

Posted on June 2nd, 2010 at 4:47 pm

For a few weeks some wise guy decided that it will be fun if he will change password to WPJobBoard demo account randomly about twice a week. Well, it wasn’t fun at all. At least for most people, so i decided that i need a plugin to disable profile update. More over i wanted to disable user, so he cannot “edit himself”.

Like you probably already guessed i wrote a plugin for that, it’s just few lines of code, so i will just paste it here:

function lockdown($user_id)
{
    global $current_user;
    wp_redirect("profile.php");
}
 
add_action('personal_options_update', "lockdown");

It’s a bit simplified version of what i am using, either way what it does is pretty much this, when someone will try to edit his profile he will be redirected to profile page, without any notification.

Note two things: while even admin won’t be able to edit his profile, he will still be able to edit other users profiles. If you would like to disable last mentioned functionality add this line to the code above:

add_action('edit_user_profile_update', "lockdown");

JavaScript date difference calculation

Posted on May 2nd, 2010 at 5:15 pm

Calculating date difference in JavaScript is almost as easy as in PHP, but requires a bit different approach. For this post i wrote simple “static” js object which can calculate difference between two dates in: days, weeks, months and years.

To each function you pass two arguments/dates, the first one should be lower then second, or you will get negative number on the output, however the number will still be valid, although with negative sign, so you just need to multiply it by “-1″.

Calculating date difference in days and weeks works pretty much the same. First we get difference between UNIX timestamps for first and second dates and then divide it by number of milliseconds in a day (for days calculation), or by number of milliseconds in a week (for weeks calculation).

Number of milliseconds in a month vary (because months have different number of days), so we are taking a different approach. For each date multiply year by 12 and add current month, that gives total number of months since year 0. Now substract both numbers and we are done.

Calculating difference between years i leave without a comment :) . Source code with example usage below.

var DateDiff = {
 
    inDays: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
 
        return parseInt((t2-t1)/(24*3600*1000));
    },
 
    inWeeks: function(d1, d2) {
        var t2 = d2.getTime();
        var t1 = d1.getTime();
 
        return parseInt((t2-t1)/(24*3600*1000*7));
    },
 
    inMonths: function(d1, d2) {
        var d1Y = d1.getFullYear();
        var d2Y = d2.getFullYear();
        var d1M = d1.getMonth();
        var d2M = d2.getMonth();
 
        return (d2M+12*d2Y)-(d1M+12*d1Y);
    },
 
    inYears: function(d1, d2) {
        return d2.getFullYear()-d1.getFullYear();
    }
}
 
var dString = "May, 20, 1984";
 
var d1 = new Date(dString);
var d2 = new Date();
 
document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2));
document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2));
document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2));
document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));

Custom WordPress comments list template

Posted on April 26th, 2010 at 9:44 pm

It’s counter intuitive but, there is no such thing as comments list template, ie the template file where you can define each comment look and feel. Of course (like with almost anything in WordPress) it’s possible to change comments list HTML, but it requires a bit different approach.

First in your theme functions.php file you need to define new function (you can call it anyway you want):

<?php
function mytheme_comment($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; ?>
   <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
     <div id="comment-<?php comment_ID(); ?>">
      <div class="comment-author vcard">
         <?php echo get_avatar($comment,$size='48',$default='<path_to_url>' ); ?>
 
         <?php printf(__('<cite class="fn">%s</cite> <span class="says">says:</span>'), get_comment_author_link()) ?>
      </div>
      <?php if ($comment->comment_approved == '0') : ?>
         <em><?php _e('Your comment is awaiting moderation.') ?></em>
         <br />
      <?php endif; ?>
 
      <div class="comment-meta commentmetadata">
          <a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>">
              <?php printf(__('%1$s at %2$s'), get_comment_date(),  get_comment_time()) ?>
          </a>
          <?php edit_comment_link(__('(Edit)'),'  ','') ?>
      </div>
 
      <?php comment_text() ?>
 
      <div class="reply">
         <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
      </div>
     </div>
<?php
        }
?>

This code was taken from WordPress Codex, at the same time it’s a default design of the single comment, you can make in this function any changes you want.

In order to implement new “comment theme” you need to configure it. Open comments.php file and find code similar to this:

<ol class="commentlist">
<?php wp_list_comments(); ?>
</ol>

wp_list_comments() function is responsible for displaying comments list. To use our custom function we defined earlier to render comments we need to pass apprioprate argument to wp_list_comments()

<?php
wp_list_comments("callback=mytheme_comment");
?>

From now on each comment will be rendered using mytheme_comment() function. wp_list_comments() accepts more actually more arguments, however i don’t want to duplicate code from Codex here, if you are interested go to WordPress Codex page for more information.

jQuery set select value

Posted on April 25th, 2010 at 9:13 pm

I still sometimes forget how to set <select> value, although it’s pretty simple. I had to “figure it out again” today so here is a quick post for future reference for me and you if you are looking for such solution.

First let’s assume there is such “select” inside “form”.

<select id="my_select" name="fruits">
    <option value="1">apple</option>
    <option value="2">orange</option>
    <option value="3">peach</option>
</select>

Now in order to set option 2 (orange) as selected on DOM ready we can execute such short snippet of code

<script type="text/javascript">
$(function() {
   $("#my_select").val(2);
});
</script>

What if <option> does not have “value” attribute? What then? That’s a homework assignment … ok i admit, i don’t know that, but on the other hand i never had to deal with select box that does not have this attribute set.

PHP list quick tip

Posted on April 14th, 2010 at 6:32 pm

It often happens that i use some function or method that returns an array of elements, but i need just the first one. Assigning this first element to variable is usually done in two lines, for example:

$arr = explode(".", "zxc.vbn.asd");
$first = $arr[0];
// $first = "zxc"

With the help of function list() it can be narrowed down to just one line:

list($first) = explode(".", "zxc.vbn.asd");
// $first = "zxc"

In my opinion that’s a neat solution for common problem, saves just a one line (and some memory), yet judging by the number of times we do “such thing” in the project i think you will find this helpful.

jQuery Image Resize Plugin

Posted on January 2nd, 2010 at 1:16 pm

Few days ago i wrote jQuery Plugin Tutorial, today i want to give away my first open source jQuery plugin: image resizer. I made sure that it’s compatible with all major browsers: IE6+, FF3, Opera10, Chrome (didn’t check with Safari, hope someone can do it for me).

The whole idea was to make it as simple as possible to resize image to given size. The common problem developers face is to resize image to (for example) no more then 150px width or no more then 75px height and because getting real image size is not as simple as it seems i think you will find this plugin useful. Read the rest of this entry »

jQuery Plugin Tutorial

Posted on December 31st, 2009 at 8:49 pm

jQuery is getting really popular lately. Employers looking for JavaScript developers often requires them to know this library inside out, so today i want to show you my practical guide to jQuery plugins development. With the emphasis on best practices in plugin development. Creating plugin is plain simple, but developing a high quality plugin is a different story. Further more it shocks me that there are tons of tutorials online that do not even make distinction between jQuery extension and jQuery Plugin. Read the rest of this entry »