A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

jQuery: Generic Image Swap

Found this little gem in Stackoverflow.

$(function() {
    $("img")
        .mouseover(function() { 
            var src = $(this).attr("src").match(/[^.]+/) + "over.gif";
            $(this).attr("src", src);
        })
        .mouseout(function() {
            var src = $(this).attr("src").replace("over", "");
            $(this).attr("src", src);
        });
});

Thanks to Jarrod Dixon.

Here is another simpler version.

$(".icons_inner img").hover(
      function(){this.src = this.src.replace("_off","_on");},
      function(){this.src = this.src.replace("_on","_off");
});

You just have to name you email images as “my_icon_on.png” and “my_icon_off.png”. I find this version a lot simpler to implement and debug. Source.

Posted in General | 2 Comments

Wordress: Using custom fields as key to sort queries with meta_query and meta_key

The example shows that I sort posts with custom field “Start Date”. I am using ‘meta_query’ to query the custom fields – you can find out more here.

$args['post_type'] = array('ur_post', 
    'programs_post', 
    'education_post', 
    'blog_post'
);
$args['meta_key'] = 'Start Date';
$args['meta_query'] = array(
    array(
        'key' => 'Start Date',
        'value' => date('Ymd'),
        'compare' => '>=',
        'type' => 'date'
    )
);
 
/*This will sort. Make sure there is no underscore. It's orderby NOT order_by.*/
$args['orderby'] = 'meta_value'; 
 
$args['order'] = 'asc';
$the_query = new WP_Query($args);
 
while ( $the_query->have_posts() ) {
    $the_query->the_post(); 
    $start_date = get_post_custom_values('Start Date', $the_query->ID);
 
    /*var_dump($custom_values);*/    
    if (date('Ymd',strtotime($start_date[0])) >= date('Ymd')) {     
        echo '<div class="event_date">';
        //display date here...
        echo '</div>';
 
        echo '<div class="event_post_time">';
        $start_time = get_post_custom_values('Start Time', $the_query->ID);
        echo $start_time[0];
        $end_time = get_post_custom_values('End Time', $the_query->ID);
        if ($end_time != NULL) {
            echo ' - '.$end_time[0];
        }
        echo '</div>';
    }
}
wp_reset_postdata();
Posted in General | Tagged , , , , , | Leave a comment

HN: Better RESTful approach

Someone (bradgessler) in HN made a very good comment in this thread.

I’m just going to copy-paste everything. Source.

The biggest problem with today’s REST implementations is that they’re essentially a database serialization layer. Consider how a RESTful Rails model is typically represented as:

  {
     book: {
        id:1,
        name:"To Kill a Mocking Bird",
        author_id:2
     }
  }

How do you get more info on the author if you only have this piece of information? Rails/ActiveResource guesses through convention: “/authors/2″, but that might not be the case, which makes this approach very brittle.
A better more “RESTful” approach might be:

  {
     book: {
        href:"/books/1",
        name:"To Kill a Mocking Bird",
        author: {
           href:"/authors/2"
        }
     }
  }

The REST client would then be able to traverse the representation without making guesses at the URL, and if the end-point of ‘/authors:id’ changes for whatever reason, the href would be updated accordingly.
Pagination/large data-sets could be solved as well:

  {
     books: [
        href:"/books/1",
        name:"To Kill a Mocking Bird",
        author: {
           href:"/authors/2"
        }
     }
    ],
    rel: {
       prev: "/books?page=1",
       next:"/books?page=3"
    }
  }

… and a bajillion other common RESTful API problems through better convention.
I’d agree with the author that REST is misunderstood, but my opinion is that its misunderstood on the grounds that today’s “REST” implementations are lame database serializations. The web has been doing this since the <a href/> tag was conceived, but for some reason, modern REST implementations left this out.

Posted in General | Tagged , | 2 Comments

New blog theme

Okay, I just spent a few days coming up with new look for the blog. It is based on the WordPress + Blueprint Barebones/Skeletal (or whatever you call it) theme. This is still a work in progress and if you find bugs/errors, post a comment or contact me ;)

Posted in General | Leave a comment

WordPress: Multi-language translation for your theme

Although, there are more advanced multi-language plugins like qTranslate available, this post will deal with basic translations in your theme. Like for example, if you want to translate a “hard-coded” English strings in your theme.

<h1>Programs</h1>

… translated into French, will display:

<h1>Programmes<h1>

when you have something like http://mysite.com?lang=fr_FR in your URL bar.

Start easy
Let’s start with the simple string above. Instead of directly outputting the string, do it like this:

<?php  
    echo '<h1>'.__('Programs').'</h1>'
?>

So, what does the double underscore (“__”) mean? The double underscore is a GetText call. There are two ways you can do a GetText call, the other way is:

    _e('Programs'); //This echoes the directly to the browser.

We use the GetText call to output the translated strings.

The translated strings
The translation are stored in a .pot file. It is a text file that looks like this:

msgid ""
msgstr ""
"Content-Type: text/plain; charset=utf-8n"
"Content-Transfer-Encoding: 8bitn"
"Project-Id-Version: n"
"POT-Creation-Date: n"
"PO-Revision-Date: n"
"Last-Translator: wenbert n"
"Language-Team: n"
"MIME-Version: 1.0n"

#: single.php:21
msgid "Programs"
msgstr "Programmes"

#: single.php:30
msgid "Contact Us"
msgstr "Contactez-nous"

You can choose to generate this file manually or use this to extract the GetText calls in your PHP files.

Generating the .mo (Machine Object) file
Once you have all the string translations in your .pot file, you will need to generate a .mo file for it. You will need POEdit to do this. It is a simple and straight forward program. You just need to import the POT file and then save it.

Save all of your files inside the “languages” folder inside your theme folder.

/mytheme/
    .. index.php
    .. single.php
    ..archive.php
    ..page.php
    /languages
        ..fr_FR.mo
        ..fr_FR.po
        ..fr_FR.pot

Triggering the translation
Put this code in your functions.php file.

add_filter( 'locale', 'my_theme_localized' );
function my_theme_localized($locale) {
    if (isset($_GET['lang'])) {
        return $_GET['lang'];
    }
    return $locale;
}
 
load_theme_textdomain( 'my_theme', TEMPLATEPATH . '/languages' );

What it does is that if $_GET['lang'] is set in the URL — and let’s say the value is set to “fr_FR” (http://mysite.com?lang=fr_FR), WordPress will look for the “fr_FR.mo” file.

Please note that this post tackles the subject in a VERY rough way. You should read further here and here — both sites were used as reference for this post!

Posted in General | Tagged , , , | Leave a comment

CSS: Simple cross-browser DIV shadows

I am posting this for myself and for my brother, John (haha).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>
<style type="text/css">
.Example_F {
 -moz-box-shadow: 0 0 5px 5px #888;
 -webkit-box-shadow: 0 0 5px 5px#888;
 /*box-shadow: 0 0 5px 5px #888;*/
 box-shadow: 0 0 5px 5px  rgba(0, 0, 0, 0.1);
 } 
</style>
<div class="Example_F">
This is a test! We use this!
</div>
</body>
</html>

Source: http://www.css3.info/preview/box-shadow/

Posted in General | Tagged , | 1 Comment

WordPress BlueprintCSS Skeletal/Bare-bones/Blank Slate Theme

It has become my habit that when designing a website, I always use the template that comes with the BlueprintCSS download. I always make sure that my design “fits” BlueprintCSS.

I am sharing my WordPress-BlueprintCSS Skeletal Theme. The theme is empty – you have to modify it to fit your design. It is also easy to modify because I have set the file templates to something like this:

<?php get_header(); ?>
<div class="container ">
    <div class="span-17" id="content">  
        <?php
                get_template_part( 'loop', 'index' );
        ?>
    </div>
    <div class="span-7 last">
        <?php get_sidebar(); ?>
    </div>
</div><!-- #container -->
<div class="container">
    <?php get_footer(); ?>
</div>

All the individual template files (page.php, index.php, single.php, etc.) are setup something like this. This way, it would be better because you will be able to specify the columns for each template.

Features

  • Easy to update columns. Columns are specified in template files (single.php, index.php, category.php, author.php, etc.
  • BlueprintCSS is located in /css/blueprint
  • Easily add your custom CSS in style.css
  • Based on the Twenty Ten theme
  • No images
  • Only the Menu and Image CSS is included in style.css – I think this is useful
  • The left side has 17 columns while the right side has 7 columns.

Download and Installation

  1. Download in Github https://github.com/wenbert/Wordpress-and-BlueprintCSS
  2. Extract to your /theme directory
  3. Enable the theme.

Please note that this is a work in progress. I encourage you to post your comments / suggestions below…

Screenshot:
. Vista :-(

Posted in General | 2 Comments

WordPress Template Hierarchy

For my personal consumption.


Posted in General | Leave a comment

WordPress: Post Types and Page Templates

Aside from the normal “Add Post” link in the WP-Admin Panel, you can add a custom post type. See http://codex.wordpress.org/Post_Types#Custom_Types.

For example, if you want to add “Videos and Podcasts” as another post type, you put this in your functions.php file:

register_post_type('videos_and_podcasts', array(
	'label' => __('Videos and Podcasts'),
	'singular_label' => __('Video/Podcast'),
	'public' => true,
	'show_ui' => true,
	'capability_type' => 'post',
	'hierarchical' => false,
	'rewrite' => false,
	'query_var' => false,
	'supports' => array('title', 'editor', 'author')
));

More details on the options can be found here.

You should be able to see something like this in your WP-Admin:

Your new custom post type is just like a normal post type.

Combining a custom post type with a Page Template

You can take things further by combining the custom page type with a Page Template. You simply have to create a PHP file that looks like this:

<?php
/*
Template Name: Landing Page Test
*/
?>
    <?php get_header(); ?>
    <h1>This is a test landing page</h1>
    <?php
    $args = array( 'post_type' => 'videos_and_podcasts', 'posts_per_page' => 10 );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    	the_title();
    	echo '<div class="entry-content">';
    	the_content();
    	echo '</div>';
    endwhile;
    ?>
 
    <?php get_footer(); ?>
<?php wp_footer(); ?>

In your WP-Admin, when you try to add a Page, you should be able to see something like this:
.

There you have it, a Page Template combined with a custom post type to display a different “frontpage” / “landing page”.

Posted in General | Tagged , , , , | Leave a comment

Django: Creating multiple select checkboxes with Forms

I got stuck for almost an hour trying to create a multiple select checkbox. Here is how to do it:

First, I put this in my forms.py

class UserlistForm(forms.Form):
    users = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,label="Notify and subscribe users to this post:")

Then in my views.py I have something like this:

def post_message(request, groupid):
    custgroup = Group.objects.get(id=groupid)
    groupusers = User.objects.filter(groups__name=custgroup.name)
 
    userlistform = UserlistForm()
 
    #This fills up the "choices"
    userlistform.fields['users'].choices = 
        [(x.id, x) for x in User.objects.filter(groups__name=custgroup.name)]
 
    data = {"userlistform":userlistform,}
 
    return render_to_response("message/view_message.html",
                          data, context_instance=RequestContext(request))

In your template, you should just display userlistform:

{{userlistform.as_p}}

EDIT:
I forgot to mention that when you want to get the “list” of selected items you use this:

userlist = request.POST.getlist('users')
"""
you will get something like this:
[u'1', u'2', u'3']
"""
Posted in General | Tagged , , , , | 3 Comments