Archive for the ‘Programming’ category

Common use snippets for Widget Logic

17/07/2012

Widget Logic is a WordPress plugin that that gives every widget an extra control field called “Widget logic” that lets you control the pages that the widget will appear on. The text field lets you use WP’s Conditional Tags, or any general PHP code.

I’ve been using Widget Logic in my WordPress projects for a while now – it’s clean, versatile and I highly recommend it.

Below are some snippets that you will likely find useful when you are building a new site.

Show widget only on specific pages or posts

This example displays the widget only on the page that has the slug example-page

is_page('example-slug')

This is my favourite way of specifying widgets for certain pages, as it works in a similar fashion to how you configure blocks for specific paths in Drupal.

This example displays the widget on pages with ID 1 and 5.

is_page(array(1,5))

is_page() is very flexible and can take id’s, page names, slugs and even arrays with multiple values – see the documentation.

But what about blog posts and attachments?

Use is_single()  instead – see the documentation.

Here is an example that display the widget when the user is visiting a post with the title “About this blog”

is_single('About this blog')

Show widget everywhere except a specific page or post.

This is the inverse of the previous examples, so the first example would be:

!is_page('example-slug')

Note the exclamation point, which inverts the logic.

The second example would be:

!is_page(array(1,5))

Show widget only on front page

Handy for front page-specific summary widgets, calendars, introductions etc.

is_front_page()

Show widget only for a specific post type

An easy way to display widgets for certain post types.

get_post_type()=='post'

Some common post types

  • page
  • post
  • attachment

Show widget based on a WPML language

If you are running a site using the WordPress Multilingual Plugin (WPML) you can use this snippet to only show a widget when the user is viewing the page in a certain language (English in this case)

(ICL_LANGUAGE_CODE == 'en')

There are more useful constants and functions available in the WPML manual.

Combining multiple rules

It’s easy to combine multiple rules with regular PHP logic. This example will display the widget only when the user is viewing a site in Swedish (WPML) and is on the pages with ID 1 or 5:

(ICL_LANGUAGE_CODE == 'sv') && is_page(array(1,5))

Don’t forget you can also use the || (or) operator!

More useful tags

I recommend reading the WordPress documentation on Conditional Tags to customize Widget Logic for your exact needs.

Feedback!

Do you have a useful snippets for Widget Logic? Feel free to post it in the comments!

Using CodeIgniter 2 with SQLite 3 databases

22/06/2012

Note: If you haven’t updated to CodeIgniter 2.1.1 – do so. There is a bug in 2.1 preventing it from working with SQLite databases properly, see the changelog.

The process of connecting to a SQLite 3 database with CodeIgniter isn’t straightforward. You have to use the (built-in) PDO driver and put the path to the database, with protocol prefix, in the hostname parameter, here’s an example:

/application/config/database.php

...
$db['default']['hostname'] = 'sqlite:'.APPPATH.'db/your_database.sqlite';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
$db['default']['dbdriver'] = 'pdo';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
...

This assumes you have your database under:

/application/db/your_database.sqlite

If the file does not exist, an empty database will be created at that location.

After you have connected, you can use the Active Record class normally to query the db, for example:

$query = $this->db->get('users');
foreach ($query->result() as $row)
{
    echo $row->id . '<br/>';
}

Remember that you need to build your table structures first with a tool such as phpLiteAdmin.


Why does the syntax differ when conecting to a SQLite 3 database?

The reason you have to put the database path in the hostname field is the way CI instantiates the PDO object:

system/database/drivers/pdo/pdo_driver.php

...
function db_connect()
{
    $this->options['PDO::ATTR_ERRMODE'] = PDO::ERRMODE_SILENT;
    return new PDO($this->hostname, $this->username, $this->password, $this->options);
}
...

Twenty Eleven Sidebar WordPress theme announcement

17/06/2012

Just put up the project page for my Twenty Eleven Sidebar WordPress theme!

Twentyeleven Sidebar is a Twenty Eleven child theme with a persistent sidebar, which means you will see the sidebar on individual posts, pages as well as media pages, such as for images.

Check out the project page, or get the code from Bitbucket!

Minimal server online status checker (HTML/JavaScript)

07/02/2012

Starbuck, noooooo!

Above is an example of a nifty server status script I have been using in a recent project.

Here is the base code for monitoring a web server:

<img src="http://site-to-check.com/online.png" alt="status" onerror="this.src='files/offline.png'" />

The setup is:

  • An online icon (online.png) on the remote server you want to see the status of.
  • An offline icon (offline.png) on the server that is going to show the status page.

If the image on the remote server fails to load, the onerror event is triggered and the javascript rewrites the image tag to show the offline image. You can use relative or absolute paths for the offline image. This snippet is fully compatible with all major browsers, including Internet Explorer down to version 5.5!

Demo
Click here for a demo.

Resources
Below are the images I use, found on Clker, an excellent online clipart resource.

Online
Offline

Participate
If you find this useful or have any suggestions for improving it, feel free to write in the comments!

Collect visitor stats using any image with the Piwik Tracking API

10/11/2011

Piwik is an open source web analytics system in PHP and a great alternative to Google Analytics.

It offers simplified tracking via an image tracking code:

<!-- Piwik Image Tracker -->
<img src="http://example.org/piwik/piwik.php?idsite=1&rec=1" style="border:0" alt="" />
<!-- End Piwik -->

In some scenarios, you might not want to expose that you are using Piwik analytics, or would like to avoid loading unnecessary resources.

Let’s use the Piwik Tracking API to turn any image into a tracker. This is useful for websites, newsletter stats and email signatures alike.

Prequisites

You need to have a Piwik install running with administrative access. Apache is required to get a “nice” image url.

Step 1 – Setup Piwik

Create a new website in Piwik, which will contain your stats for the image. Make note of the new site ID (Visible in Settings > Websites)

Create a new user and give that user admin rights to the website. Make note of the token_auth for that user. (Under Settings > Users)

Step 2 – Get the PiwikTracker.php Tracking API

You can obtain this file by going to the following URL (Replace example.org with your piwik install path)

http://example.org/piwik/index.php?module=SitesManager&action=downloadPiwikTracker&idSite=$IDSITE&piwikUrl=http://example.org/piwik/

You can also find a copy of the file here.

Step 3 – Build the tracking code
Pick an image you’d like to use, name it stats.png and put it in a folder on your web server. I am going to use this “thumbs up” clipart. Also put PiwikTracker.php in this folder.

Now, create the file stats_t.php. (Base code below) Change line 3 and 4  to your own site id and the token_auth of the user you created in step 2. Also set your Piwik URL at line 10. If you want to distinguish between multiple tracking images, you can change line 22 to have a different message. That means you can track any number of images using one site in Piwik.

<?php
    //Set the id of your piwik site here
    $idSite = 1;
    $token_auth = 'your user token here';

    //Load Piwik Tracker
    require_once 'PiwikTracker.php';

    //Set the URL path to your Piwik Installation
    $t = new PiwikTracker($idSite,'http://example.org/piwik');

    //Auth to allow for more API functions
    $t->setTokenAuth($token_auth);

    //Set correct IP (Should be users, not the web server issuing the request)
    $t->setIp($_SERVER['REMOTE_ADDR']);

    //Set referrer (if applicable)
    if(isset($_SERVER['HTTP_REFERER']))
       $t->setUrl($_SERVER['HTTP_REFERER']);

    $t->doTrackPageView('Image viewed');

    $im = imagecreatefrompng("stats.png");

    //For transparency (Alpha blending)
    imagealphablending($im, true);
    imagesavealpha($im, true);

    //Set header
    header('Content-Type: image/png');
    //Output image
    imagepng($im);
    //Unload image
    imagedestroy($im);
?>

You can set many more visitor details, refer to the reference.

Create a .htaccess file in the same folder. We will use this to rewrite the URL so that we can still use a .png extension for the file. When stats_t.png is called, Apache will instead load stats_t.php , which will run the tracking code.

RewriteEngine On
RewriteRule stats_t.png stats_t.php

Your folder structure should now look like this:

Verify that your image is displayed properly in a web browser by navigating to stats_t.png

Verify that Piwik recorded the visit correctly. If it did not, make sure you have entered $token_auth and $idSite correctly.

Step 4 – Display your new tracking image anywhere

Now you can include your image anywhere, like this:

<img src="http://khromov.se/email2/stats_t.png" alt="thumbs up" />

If you would like more information please see the official documentation of the Tracking API.

Let me know if this helped you out or if you have any suggestions or improvements!

Update: Now includes referrer tracking. If the image is used on a page, you will see what page it is used on. (See line 19 and 20 of stats_t.php)

PHP function for obfuscating e-mail addresses and phone numbers using Javascript.

04/10/2011

Update 2012-12-23

The technique below is now available as a WordPress plugin. Check out the Email Obfuscate Shortcode plugin!

Here’s a short snippet that I have been using in various PHP projects to protect e-mail addresses and phone numbers against being harvested for spam purposes. It uses Javascript to scramble some text and output it as a self-contained piece of Javascript. It’s compatible with all major browsers (and IE5.5 and up). The idea is based on this ruby snippet, so head over there if you want to read more about the way it works!

safe_text() snippet

function safe_text($text)
{
    if(mb_detect_encoding($text, 'UTF-8', true))
        $text = utf8_decode($text);

    $ret = '
<script type="text/javascript">// <![CDATA[
                    var t=[
                ';
    $chars = str_split($text);

    $enc[] = rand(0,255);

    foreach($chars as $char)
    {
        $enc[] = ord($char)-$enc[sizeof($enc)-1];
    }

    $ret .= join(',',$enc);
    $ret .= '
                ]; for (var i=1; i<t.length; i++) { document.write(String.fromCharCode(t[i]+t[i-1])); }
// ]]></script>';

    return $ret;
}

To output the Javascript anywhere (it’s entirely self-contained), simply run:

echo safe_text('bob@examplecorp.com');

Update: Thanks to Fredrik for a fix that makes this function multibyte safe! It now also works with special characters like å,ä,ö and similar.

15 web design resources that will save you time and improve your designs!

25/03/2010

I have been doing quite a lot of creative work recently in the domain of web design (get it, “domain”, har har!) , and I’d be happy to share some of the great web sites and applications that have helped me make better and cleaner design and code jobs. I have divided the sites into six categories, so take your pick and dig in!

If you have any suggestions of your own, I’d be happy to hear them, leave a comment and be heard!

Cliparts and photos

image 

Sxc.hu – Royalty free photography
Sxc.hu, or stock.xchng, is the little brother of  iStockphoto. They offer royalty-free photography for non-commercial use, and an option to contact the authors for use in commercial application using a very relaxed license. My experience with the people there has been great as a whole, highly recommended and great array of photographs, but also clip art.

image 

clker.com – public domain clip art
Clker.com offers public-domain clip art uploaded by users. Great site for any smaller images that you might need, such as bullets and icons.

Compatibility

image

Common font list
When designing a page, you need to make sure you use a font that is visible to and looks visually similar for every viewer, and degrade gracefully in the cases where the font is not present on the viewers computer. This useful webpage displays common font families that work over a wide array of browsers and operating systems.

Inspiration

image

BrowserShots
BrowserShots has lost its glory days as the go-to site for making sure your web pages look equal across all browsers due to its increasingly long rendering waiting time and restrictions, and with IETester mentioned below, you can verify that your page runs properly on all major browsers.

But BrowserShots has introduced a fantastic gallery of web designs, and this is a place where you can find great inspiration.

image

ColorSchemer gallery and ColourLovers palette gallery
Finding the correct colors for your site can be a surprisingly difficult challenge, but when browsing these galleries, this becomes a fun experience. The idea is that you pick a scheme, which contains roughly 3-8 colors, and then try to base your design around these. If you try it, you’ll find a surprisingly clean and beautiful site looking back at you when you are finished. Using schemes with multiple variation of the same color (like this one) has worked the best for me.

image

Web Design From Scratch
A great resource for articles about the philosophy behind, and practical application to modern web design.

Applications/Add-ons

image

Sizer
Sizer is a small application which allows you to easily resize your browser (or really, any) window to see your web pages (hopefully) degrade in a graceful manner. Simple and easy, yet invaluable.

image

Firebug (Firefox add-on)
Firebug is a great web developer tool built as a Firefox add-on. I have barely scraped the surface of this great tool, but it has been very helpful so far.

image 

IETester
Your web design and CSS looks great in the latest versions of Firefox, Chrome, Opera and IE? You’re not done yet! Unfortunately, a large portion of people still use Internet Explorer 7 and 6 (*shudders*) and this tool will help you make sure your design stays true to its form. (although it probably won’t until you spend an hour trying to figure out why IE6/7 doesn’t handle inline block  properly, which brings us to…)

Fixes and hacks for common problems
  image

Google
This might seem like an odd choice at first, but if you’ve ever had a problem, googling will almost always lead to an answer. The great thing about the internet is that chances are great that somewhere, someone has had your exact problem and either asked about it in a forum or given a solution in a blog post, which will usually lead you closer to an answer.

image 

IE PNG Fix
It is fairly common knowledge that Internet Explorer 6 and below does not handle the alpha channel (transparency) for PNG images properly and displays the whole transparent area as a gray box. Resorting to GIF is possible for single-colored background, but for patterned backgrounds your only choice is PNG and this fix (Which is mostly done in CSS) will take care of that.

A quick note: I have noticed that the JavaScript used for tiling images in “IE PNG Fix”, which is called “iepngfix_tilebg.js” seems to break the dropdown functionality of Superfish, which I mentioned earlier. I have been looking at the problem, but haven’t been able to identify the culprit, although I suspect it is related to the way the JS places the image. Unless you absolutely need tiling support, it’s best not to use the JS code, so beware!

image
CSS Sticky Footer
Making a footer that always stays at the bottom of the page, moves with JavaScript and  works over all major browsers is a surprisingly difficult task, but CSS Sticky Footer takes care of it. It requires you to import a fairly large CSS file, but it shouldn’t break your layout too much, aside from a margin that needs fixing here and there.

Coding
 image

CodeIgniter PHP Framework
CodeIgniter is a great framework for easily making web applications in PHP. The features I have enjoyed so far is the fantastic database handling using Active Record, the interesting Model-View-Controller approach (which was new to me) and the great performance I get from my applications. If you want to know what the hype is about, check out this video tutorial entitled “Create a blog in 20 minutes”!

image

Suckerfish JavaScript/CSS menu system
Another thing that seems like there should be a myriad of online, but is surprisingly difficult to find is a menu that works over all browsers, is completely free, simple to use and can be used in commercial applications. Look no further, Suckerfish is what you have been waiting for! And it degrades nicely to CSS-only under environments without JS too!