How to add a “delete” button to WordPress admin bar

To apply this tip, simply paste the following code into your functions.php file:

<?php
function fb_add_admin_bar_trash_menu() {
  global $wp_admin_bar;
  if ( !is_super_admin() || !is_admin_bar_showing() )
      return;
  $current_object = get_queried_object();
  if ( empty($current_object) )
      return;
  if ( !empty( $current_object->post_type ) &&
     ( $post_type_object = get_post_type_object( $current_object->post_type ) ) &&
     current_user_can( $post_type_object->cap->edit_post, $current_object->ID )
  ) {
    $wp_admin_bar->add_menu(
        array( 'id' => 'delete',
            'title' => __('Move to Trash'),
            'href' => get_delete_post_link($current_object->term_id)
        )
    );
  }
}
add_action( 'admin_bar_menu', 'fb_add_admin_bar_trash_menu', 35 );
?>

Thanks to WP Engineer for the great hack!

How to display RSS feeds on your WordPress blog

The following code have to be pasted wherever you want to display the feed.
Don’t forget to update the feed url on line 3. Number of items to be displayed can be defined on line 6.

<?php
include_once(ABSPATH . WPINC . '/rss.php');
$feed = 'http://example.com/feed/';
$rss = fetch_feed($feed);
if (!is_wp_error( $rss ) ) :
    $maxitems = $rss->get_item_quantity(3);
    $rss_items = $rss->get_items(0, $maxitems);
    if ($rss_items):
        echo "<ul>\n";
        foreach ( $rss_items as $item ) :
            echo '<li>';
            echo '<a href="' . $item->get_permalink() . '">' . $item->get_title() . "</a>\n";
            echo '<p>' . $item->get_description() . "</li>\n";
        endforeach;
        echo "</ul>\n";
    endif;
endif;
?>

Thanks to Dan Gayle for the hack!

10+ WordPress page templates for all needs

Contact form page template


This tutorial will show you how to create a page template which will display a contact form so your readers can reach you. It do not require any plugin to work.
Link: http://www.catswhocode.com/blog/how-to-create-a-built-in-contact-form…

Redirect template


If you need to be able to redirect visitors to another page, including an external site, this page template is for you. Simple an efficient!
Link: http://www.dynamicwp.net/articles-and-tutorials/how-to-create…

Custom query page template


This one might sounds basic at first, but custom queries are something you often use when building WordPress based websites, so knowing how to create custom queries page templates is a must for all developers working with WordPress.
Link: http://www.tammyhartdesigns.com/wordpress/wordpress-create-a-page-template…

Landing page template


Landing pages are very popular on the web, for example to welcome visitors before the official launch. Here is a simple tutorial to help you build a landing page template.
Link: http://nxnweb.com/landing-page-template-wordpress/

Image gallery page template


The guys from the Tuts+ network always have cool tutorials, and this one is just amazing. It will show you how to create an awesome image gallery page template using some jQuery.
Link: http://wp.tutsplus.com/tutorials/creating-your-own-image-gallery-page-template-in-wordpress/

Registration page template


A complete tutorial about how to create a page template where users can register. The whole code could certainly have been better, but still a big time saver if you’re in a hurry.
Link: http://www.tutorialstag.com/create-custom-wordpress-registration-page.html

Sitemap page template


An HTML sitemap is often mentioned as being useful for SEO. It is also very useful for visitors who need to find a particular page without having to dive deep in your website archive.

This tutorial will show you how to easily create a sitemap for your WordPress blog or website.
Link: http://yoast.com/html-sitemap-wordpress/

RSS page template


Here is a cool code snippet to import any RSS feed on WordPress. This can be easily turned into a page template, so you’ll be able to display a feed from another website on your own site.
http://www.dangayle.com/import-feeds-wordpress-fetch-feed/

Google+ feed page


Here is the full code to build a Google+ stream page template for your WordPress based website.
Link: https://gist.github.com/1496148

Private page template


If you want to restrict some of your content to registered users, here is a tutorial that you’re definitely going to enjoy. It will show you how to create a page template that display content only to logged in users and display a login form to other visitors.
Link: http://www.marketingtechblog.com/login-content-wordpress-page-template/

Author page template


Another cool Tuts+ tutorial, which explains how to build pages that display information about authors. Especially useful when running a multi-author blog!
Link: http://wp.tutsplus.com/tutorials/how-to-create-a-wordpress-authors-page-template/

Page template to redirect to child page


Let’s finish this article with another useful piece of code, which allow you to automatically redirect visitors to the first child page if the current page have children pages. This is quite useful when working with dropdown menus!
Link: http://www.wprecipes.com/wordpress-page-template-to-redirect-to-first-child-page

How to automatically add a class to body_class if there’s a sidebar

To apply the hack, just paste the code below into your functions.php file.

function wpfme_has_sidebar($classes) {
    if (is_active_sidebar('sidebar')) {
        // add 'class-name' to the $classes array
        $classes[] = 'has_sidebar';
    }
    // return the $classes array
    return $classes;
}
add_filter('body_class','wpfme_has_sidebar');

Thanks to WP Function for the tip!

WP Theme Generator giveaway!

How to enter the giveaway

To enter, simply tweet anything including our partner url: http://www.wpthemegenerator.com. Then, leave a comment on this page so I’ll have your email address. In one week (May 25), I’ll pick 5 winners using Random.org and they’ll receive their prizes directly from the WP Theme Generator staff.

Some more info about WP Theme Generator

WordPress Theme Generator is a master tool to create and design custom themes, for it comprises more than 1000 design elements at your disposal and supports your own uploaded designs if so you wish. Additionally you can download all your themes –with a full-of-features framework– or save them for later review or edition, both in WP or HTML, and while they are being kept within the tool’s interface, they are kept up-to-date with the latest framework releases. If time is of the essence and an even faster solution is required there’s a public themes gallery which has hundreds of professionally pre-designed themes that include layered .psd files.

WordPress Theme Generator main features

  • 1000+ Pre-designed elements
  • New design elements added daily
  • Change any design aspect with an easy to use interface
  • 50+ preloaded fonts to to choose from
  • Unlimited sidebars or widget areas
  • Saving, editing and downloading of the themes
  • Download in both WP & HTML/CSS
  • Always updated with the latest WP version
  • A powerful framework behind
  • Check all features

Take a look to the WordPress Theme Generator.

How to automatically create meta description from content

Paste the following code into your functions.php file:

function create_meta_desc() {
    global $post;
if (!is_single()) { return; }
    $meta = strip_tags($post->post_content);
    $meta = strip_shortcodes($post->post_content);
    $meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
    $meta = substr($meta, 0, 125);
    echo "<meta name='description' content='$meta' />";
}
add_action('wp_head', 'create_meta_desc');

Thanks to Paul for this handy snippet!

Tips and best practices to develop responsive websites

Start with a template


Sure, you can start coding from scratch, but there’s a lot of interesting free templates that will make you save a lot of time. Among others, I recommend Mobile boilerplate, The 1140 grid and Skeleton. There’s a lot more than those ones, so feel free to google “responsive web design template” if you want more.

Working with fluid grid based layouts


Fluid layouts are an important part of a good responsive layout. In order to have a website that can adapt to many different screen resolutions, you have to use a fluid layout with widths defined in percents instead of pixels.

To get the size in percents from a size in pixels, you have to take the element’s width and divide it by the full grid size. For example: 200 px (element size) / 960 px (grid size) = 0.2083. Multiply this by 100, and you’ll get 20,83%.

This is why it is interesting to work with a 1000px grid. 1000 is a round number, and it is easy to calculate that 24% of this size will be equal to 240 pixels. For more info about 1000px grids, I recommend you to check out this article.

Flexible images

A very important aspect of a responsive layout is how images can adapt to the size of their parent container. The basic solution is to define a maximum width of 100%. This will make sure that your images are never wider than the parent container.

.content img{
   max-width:100%;
}

A better solution is to use context-aware image sizing. This technique basically consists of having different sizes of an image, and displaying only the size adapted to the device. Quick example:

<img src="image.jpg" data-src-600px="image-600px.jpg" data-src-800px="image-800px.jpg" alt="">

And the related CSS:

@media (min-device-width:600px) {
    img[data-src-600px] {
        content: attr(data-src-600px, url);
    }
}

@media (min-device-width:800px) {
    img[data-src-800px] {
        content: attr(data-src-800px, url);
    }
}

For more info about this technique, check out this article.

jQuery is your friend

jQuery is definitely a super useful tool when it comes to web development. Lots of jQuery plugins can help you to create better responsive websites.
A quick round up of my personal favorites:

  • FitText: A plugin that makes font-sizes flexible.
  • Elastislide: A responsive jQuery carousel plugin.
  • Supersized: A fullscreen background slideshow plugin.
  • FitVids: A lightweight, easy-to-use jQuery plugin for fluid width video embeds.

Don’t forget Apple’s viewport

The <meta name="viewport""> tag was introduced by Apple for their mobile devices (iPhones, iPads and iPods Touch). This tag allow you to specify the default size of a page when viewed with an iPhone or iPad.

<meta name="viewport" content="width=device-width; initial-scale=1.0">

The code above will ensure that upon opening, your layout will be displayed properly at 1:1 scale. No zooming will be applied.

For more info, feel free to check out Apple developper documentation.

Scalable background images

The CSS3 specification introduced a new attribute named background-size. As you probably guessed, it is used to define the size of background images. It can be a size in pixels, or it can use some of the reserved keywords. The cover keyword scale the background image (while preserving original proportions) to be as large as possible so that the background positioning area is completely covered by the background image.

html {
	background: url(bg.jpg) no-repeat center center fixed;
	-webkit-background-size: cover;
	-moz-background-size: cover;
	-o-background-size: cover;
	background-size: cover;
}

The solution above works perfectly in Chrome, Safari 3+, IE 9+, Firefox 3.6+ and Opera 10+. If you’re looking for a solution that works in older browsers, I highly suggest using this jQuery plugin or one of the alternative CSS tweaks published here.

Get inspired


When designing a website, it is always good to be able to get inspired by what others have done. Since the rise of responsive web design, online galleries have been created to showcase the best responsive websites.

The most complete gallery is definitely mediaqueri.es, but if you need some more inspiration, you can get it here or here.

Test, test, test, and test again!


Indeed, when developing a responsive layout, you have to test it in different resolutions. Of course, you can manually resize your browser, but why not using one of the useful tools created to simplify this task?

Lots of differents tools are available for you to test your website in different screen sizes. At the moment, my favorites are definitely ScreenQueri.es and Resize my browser.

How to Remove the Width and Height Attributes From WP Image Uploader

Simply paste the following code into your theme functions.php:

add_filter( 'post_thumbnail_html', 'remove_width_attribute', 10 );
add_filter( 'image_send_to_editor', 'remove_width_attribute', 10 );

function remove_width_attribute( $html ) {
   $html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
   return $html;
}

Thanks to Damien for the cool hack!

Super useful online tools to work with images

Minus


As a developer or designer, you often need to upload images for sharing them with clients or people you work with. Many websites allow you to do so, but what I really love with Minus is how quick and easy it is: Just drop your image on their website, and it’s online. They’ll even give you a short url so you can share your image easily. No registration required!

Just one request, I hope they’ll add a resize image feature soon.
→ Visit Minus

Smush It


When using images on the web, one thing you must definitely think about is the image size. You need to find the good balance between image weight and quality. Smush It is a tool developed by Yahoo! which allow you to optimize your images without loosing quality. WordPress users, note that there’s a WP plugin available.
→ Visit Smush It

Placehold It


When creating a website layout, you often need placeholder images of an exact size. Placehold It allows you to dynamically create placeholder images. To use it in your designs, simply use urls like this: <img src="http://placehold.it/350x150"> to display a 350*150 pixels placeholder image.
→ Visit Placehold It

Resize images online


Don’t want to open Photoshop just for resizing an image? This site is here to help. Just upload your image, specify the desired size, and you’re ready to go!
→ Visit Resize images online

Photoshop online tools


When it comes to image editing, Adobe Photoshop is definitely the most popular software. Adobe launched a light version of Photoshop which is available online. The online app is quite powerful and have many features. Unfortunely you have to register to use Photoshop online.
→ Visit Photoshop online tools

Pixlr express


Pixlr express is a simple but powerful app which allow you to resize images, add effects, borders, watermarks, etc. The app is free and do not require registration.
→ Visit Pixelr express

Aviary Phoenix


Developed in Flash, Aviary Phoenix is a super-complete and free online image editor. A real “light photoshop” that you can access from any computer, without any registration.
→ Visit Aviary Phoenix

I just created a Facebook page for Cats Who Code, so don’t hesitate to become a fan!

How to redirect users to a random post

Create a new file and name it page-random.php. Paste the code below in it:

// set arguments for get_posts()
$args = array(
    'numberposts' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = get_posts ( $args );

// process the database request through a foreach loop
foreach ( $my_random_post as $post ) {
  // redirect the user to the random post
  wp_redirect ( get_permalink ( $post->ID ) );
  exit;
}

Once done, upload the page-random.php file to your theme directory. Then, login to your WordPress dashboard and create a new page, called “random” (You have to call it random, otherwise, the standard page layout will apply, see WP Codex for more details about page hierarchy).

After you published the random page, any user who’ll visit the http://www.yourwebsite.com/random page will be automatically redirected to a random post.

By the way, I just created a Facebook page for my websites (This include WPRecipes as well as CatsWhoCode) so don’t hesitate to “like” it!

Thanks to Smashing Magazine for the cool tip!

Super useful WordPress action hooks and filters

Prevent automatic image compression

By default, WordPress compress jpg images when you upload them to your blog. This is useful because it saves bandwidth and loading time, but sometimes you may prefer to have full quality images (For example, if you’re a photographer using WordPress to showcase your work).

Paste the code below into your functions.php file to remove automatic compression of images.

add_filter('jpeg_quality', function($arg){return 100;});

→ Source: http://www.wprecipes.com/prevent-wordpress-to-compress-your-jpg-images

Add target=”blank” to all links

I’ve never been a fan of target="blank" links, but I’m always surprised to see how clients love them. So if you need to transform all links to target="blank" links, here is an easy solution.

This function have to be pasted in your functions.php file.

function autoblank($text) {
	$return = str_replace('<a', '<a target="_blank"', $text);
	return $return;
}
add_filter('the_content', 'autoblank');

→ Source: http://www.catswhocode.com/blog/snippets/add-target_blank-on-all-link

Add extra contact methods to user profiles

By default, WordPress allow users to enter an AIM name on their profile, but no Facebook and no Twitter names! But in 2012, those websites are far more popular than the good old AIM (ah, memories…).

In order to add more contact methods to user profile, simply paste this hook in your functions.php file. In this example it will add Facebook and Twitter, but it can be used for any website or service you need.

function my_user_contactmethods($user_contactmethods){
  $user_contactmethods['twitter'] = 'Twitter Username';
  $user_contactmethods['facebook'] = 'Facebook Username';

  return $user_contactmethods;
}

add_filter('user_contactmethods', 'my_user_contactmethods');

→ Source: http://wp.tutsplus.com/tutorials/quick-tip-add-extra-contact-methods-to-user-profiles/

Remove the “read more” jump

On WordPress blogs, when you click on a “Read more” link, it automatically drops to the point in the article you theoretically just got to the end of. If you don’t really like that jump, simply paste the following code into your functions.php file to get rid of it.

function wdc_no_more_jumping($post) {
     return '<a href="'.get_permalink($post->ID).'" class="read-more">'.'Continue Reading'.'</a>';
}
add_filter('excerpt_more', 'wdc_no_more_jumping');

→ Source: http://wpshout.com/wordpress-functions-php/

Automatically enable threaded comments

By default, WordPress do not enable threaded comments. If you want/need to change this, here is a handy code snippet to paste in your functions.php file:

function enable_threaded_comments(){
 if (!is_admin()) {
  if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1))
   wp_enqueue_script('comment-reply');
  }
}

add_action('get_header', 'enable_threaded_comments');

→ Source: http://wpshout.com/wordpress-functions-php/

How to show an urgent message in the WordPress admin area

When writing custom WordPress theme or plugins, you might want to inform users that something important needs doing, perhaps due to an upgrade. e.g. You need the user to update a setting, or check that their settings have been transposed correctly. Here is a ready to use hook to display a custom message to admins.

function showMessage($message, $errormsg = false){
	if ($errormsg) {
		echo '<div id="message" class="error">';
	} else {
		echo '<div id="message" class="updated fade">';
	}

	echo "<p><strong>$message</strong></p></div>";
}  

function showAdminMessages() {
    showMessage("You need to upgrade your database as soon as possible...", true);

    if (user_can('manage_options') {
       showMessage("Hello admins!");
    }
}

add_action('admin_notices', 'showAdminMessages');

→ Source: http://www.wpdoctors.co.uk

Automatically replace words in your posts

Imagine this: your blog was named “myblog” and for some reason you renamed it “mysuperblog”. Don’t edit your XXX posts to replace every single occurence! Instead, paste this useful hook into your functions.php file and let it do the work for you.

function replace_text_wps($text){
    $replace = array(
        // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
        'wordpress' => '<a href="#">wordpress</a>',
        'excerpt' => '<a href="#">excerpt</a>',
        'function' => '<a href="#">function</a>'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}

add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');

→ Source: http://wpsnipp.com/

Add post thumbnails to RSS feed

This very cool piece of code will get the post thumbnail and automatically add it to your RSS feeds. Paste the code into functions.php and save the file. Don’t forget that you need to use a theme that supports post thumbnails for this snippet to work.

function cwc_rss_post_thumbnail($content) {
    global $post;
    if(has_post_thumbnail($post->ID)) {
        $content = '<p>' . get_the_post_thumbnail($post->ID) .
        '</p>' . get_the_content();
    }

    return $content;
}
add_filter('the_excerpt_rss', 'cwc_rss_post_thumbnail');
add_filter('the_content_feed', 'cwc_rss_post_thumbnail');

→ Source: http://snipplr.com/view.php?codeview&id=56180

Quick maintenance mode

Sometimes, you need to put your blog on hold while performing some maintenance. Many plugins are allowing you to do so, but here is a simpler solution: Just paste the following snippet into your functions.php file and save it. Your blog is now unavailable to anyone except administrators. Don’t forget to remove the code when you’re done with maintenance!

function cwc_maintenance_mode() {
    if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
        wp_die('Maintenance, please come back soon.');
    }
}
add_action('get_header', 'cwc_maintenance_mode');

→ Source: http://skyje.com/2011/05/wordpress-code-snippets/

Remove comments autolinks

If someone leaves a comment containing a url on your WordPress blog, the url will be automatically transformed to a link by WordPress. This can be useful, but personally I don’t like to see many links in comments, especially when they’re a bit spammy.
Removing autolinks is pretty easy: Just paste the following code into your functions.php file: Once you saved the file, you’ll notice that autolinks have disappeared.

remove_filter('comment_text', 'make_clickable', 9);

→ Source: http://www.wprecipes.com/wordpress-hack-remove-autolinks-in-comments

How to change the “posts” label to “articles”

Nothing complicated: Open your functions.php file, paste the code below in it. Save the file, and you’re done!

add_filter('gettext',  'change_post_to_article');
add_filter('ngettext',  'change_post_to_article');

function change_post_to_article($translated) {
     $translated = str_ireplace('Post',  'Article',  $translated);
     return $translated;
}

Thanks to Smashing Magazine for the cool tip!

Awesome sites to find useful code snippets

CatsWhoCode snippet library


Some of you already know it, but a few weeks ago I’ve created a snippet library with a picky selection of usefull snippets focused on web development: PHP, JavaScript, CSS, htaccess… Approximately one new snippet is published every day. Users are welcome to submit their own snippets.
→ Visit CatsWhoCode snippet library

Snipplr


Snipplr is probably the largest code snippet repository available on the internet. Since 5 years, they have published thousand of pieces of code. Some snippets are super useful, some other not so, but there’s a strong chance that you’ll find what you need on a website with so many snippets.
→ Visit Snipplr

WPRecipes


Another site of mine, where I publish only WordPress related snippets since 2009. More than 300 snippets are available, so don’t miss it if you work with WordPress!
→ Visit WPRecipes

PHP Snips


Are you into PHP? If yes, you’ll for sure love PHP Snips, a PHP-only code snippets library. Hundreds of snippets are freely available, most of them are very useful and well coded.
→ Visit PHP Snips

DZone code snippets


DZone Snippets is a public source code repository, hosted by popular developer website DZone. Thousands of snippets in more than 25 languages are available. As it is 100% user powered, quality is very mixed: some snippets are useful and well coded while some other are a complete waste of time.
→ Visit DZone code snippets

Jonas John snippet library


Currently 143 quality code snippets, covering PHP, C#, Visual Basic, JavaScript, and more. A good resource to keep in your bookmarks!
→ Visit Jonas John snippet library

Code Beach


Code Beach is a central repository where Mac developers can share pieces of useful code in all programming languages used on Mac: Objective C, Ruby, C, C++, Python… Don’t miss it if you’re a Mac developper!
→ Visit Code Beach

CodeKeep


With more than 18,000 code snippets, there’s a strong change that you’ll find what you need on CodeKeep. The site have compiled snippets in various languages such as C#, C++, ActionScript, ASP, VB and more.
→ Visit CodeKeep

Code Codex


Using the poipular wiki formula, Code Codex is a website where you can find and add lots of snippets in languages like C, C++, Java, Perl, and more.
→ Visit Code Codex