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!

Display WordPress login form anywhere in the theme

Posted on August 8th, 2010 at 11:31 am

WordPress 3.0 (among the other cool features) allows to display login page anywhere in the theme or even in the post itself (if you write a plugin of course), it’s actually done with just one line of code.

wp_login_form()

This code will “echo” the form (it’s a simple form without any styling applied to it so that’s a good thing). Like with everything in WordPress wp_login_form allows for easy customization by passing array of arguments to the function. I won’t describe it here checkout function source in wp-includes/general-templates.php line 250 (we are talking WP 3.0 of course).

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 »

Finally 100 posts on Ditio

Posted on June 2nd, 2010 at 5:01 pm

I usually don’t publish more then one post a week, but this is really important after almost 3 years ditio.net reached 100 posts mark. At the same time the blog is almost 3 years old (actually the domain will be 3 years old on June 6th).

Either way 3 years is about 1095 days, which means that i have pathetic post frequency of 0.1 post/day. Or rather it’s the blog posts frequency since in the past i hired people to write for me. I am even afraid to check how much of this posts were actually mine.

Ok, so i am awaiting congratulations now :)

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");

Expert PHP 5 Tools – book review

Posted on May 10th, 2010 at 9:27 pm

Some time ago nice people from Packt Publishing sent me review copy of Expert PHP 5 Tools book written by Dirk Merkel. The book has 437 pages, so it took me a while to read it and create a review.

My first impression is that book was created mainly for advanced users, there is no place for teaching reader PHP programming, author assumes your skilled enough to get thru it and understand the source, more over the book is not that much about programming itself. So what’s it about? I think that statement from the cover page sums it nicely “Proven enterprise development tools and best practices for designing and deploying PHP applications”.

First two chapters are about source code: coding standards and documentation with PHPDoc. Basically if you read Zend Framework coding standards, you can skip at least first of this chapters. I also had quite strange feeling that author implies that only “his” coding standards are the only good ones – which is well … not true.

From the chapter 3 we get to the nuts and bolts of the book … expert tools. First one is Eclipse with PDT extension. If phrase Integrated Development Environment (or IDE) tells you nothing you should really check out this chapter. Using IDE is one of the easiest ways to improve your development speed and Dirk explains exactly how to do it.

Chapter four is all about SVN. If you are not using yet some version control system this chapter is a great way to get you started … and by the way, if you are not using version control you are shooting yourself in the foot. Chapter five covers debugging (mainly) with XDebug. I liked it. I did not realize that there are so many options available in XDebug.

Chapter 6 is about PHP Frameworks, it describes briefly some of the most popular frameworks and than focuses on the Zend Framework, i find it as nice and detailed introduction to ZF. Next chapter is about Unit Tests. I have to admit i was never a big fan of unit testing, but if you want to learn how to do it the right way this chapter will do it for you.

Last three chapters (8, 9, 10) are about automation in terms of: application deployment, design and development. Automation is one of the best thing you can do for your application, the less human interaction is needed for deployment the smaller are chances of making a mistake. I think that deployment is one of the most important “things” any developer does (especially if you are just updating live sites) so i guess that every professional developer should take some time to read about it.

Despite there were parts i didn’t liked that much i find this book very informative and innovative in a way that author presented how PHP applications/software should be developed. I think that if you have your programming skills nailed down “Expert PHP 5 Tools” book is a natural step to become a better developer.

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.