How to only display the author posts in the admin post list

Paste the code below into your functions.php file. Once you saved the file, authors will only see their own posts in the admin post list.

<?php

function mypo_parse_query_useronly( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/edit.php' ) !== false ) {
        if ( !current_user_can( 'level_10' ) ) {
            global $current_user;
            $wp_query->set( 'author', $current_user->id );
        }
    }
}

add_filter('parse_query', 'mypo_parse_query_useronly' );

?>

Thanks to WP Snippets for the code!

LawyerWordPressThemes giveaway: Win an awesome theme for your blog

About Lawyer WordPress Theme

Our sponsor is LawyerWordPressThemes, a new WordPress premium theme seller which specialize in the law/attorney niche. But of course, the “Lawyer” theme can be used for any activity you want to. It’s a visually pleasant theme built on quality code.

How to join the giveaway?

Joining the giveaway is free and easy: Just leave a comment on this post to take part to the contest. In one week (wednesday March 20) I’ll randomly pick one lucky winner and I’ll send him a coupon code that will allow him to get the theme for free. That’s it! Good luck everyone!

How to run the loop outside of WordPress

Paste the following code on any PHP file where you want to run your WordPress loop. Don’t forget to modify the following:
line 4: Please specify the path to your WordPress wp-blog-header.php file.
line 5: Query posts using the query_posts() function.

<?php
  // Include WordPress
  define('WP_USE_THEMES', false);
  require('/server/path/to/your/wordpress/site/htdocs/blog/wp-blog-header.php');
  query_posts('showposts=1');
?>

<?php while (have_posts()): the_post(); ?>
   <h2><?php the_title(); ?></h2>
   <?php the_excerpt(); ?>
   <p><a href="<?php the_permalink(); ?>" class="red">Read more...</a></p>
<?php endwhile; ?>

Thanks to CSS Tricks for the great tip!

Ultimate list of WordPress resources

Starter kits, blank files and generators


When developing a WordPress theme, widget or plugin, the best way to start is by using a “blank” template file so you’ll save time and you’ll start on solid foundations. Here are my favorites:

  • Underscores.me: in my humble opinion, the best way to start coding a new WordPress theme. Simply fill the options and you’ll get offered to download a rock solid blank WordPress theme template.
  • WP Widget Starter file: a blank template for developing WordPress widgets.
  • Plugin Starter: a base class that is easily extended to make plugin development better, faster and stronger.
  • WP Starter Kit: a development template for rapidly building WordPress plugins.
  • Threaded comments: Basic CSS styles for threaded comments. Always a good start when it comes to styling comments!

WordPress Hosting


Basically, it is pretty easy to find a suitable webhost to host a WordPress site or blog. Though, I do recommend the following hosts for the good results I had with them since years:

  • Vidahost: CatsWhoCode webhost. Super fast, reliable, no down time and a super friendly and reactive support. It’s not cheap at all, but definitely the best option if your site is receiving a lot of traffic, or if you’re looking to host multiple sites on a single server.
  • WP Web Host: The webhost I recommend for people looking for an affordable and easy way to host a WordPress based website or blog. Friendly support with strong WordPress knowledge. Good service for small/medium sites.

On the other hand, I do not recommend Maven Hosting and PHPNet as I had bad results with both of them. I never hosted any of my websites on Bluehost, but I worked with a client who did and I didn’t found the performances good.

Free themes


There’s literally thousands of WordPress themes that you can download and use freely on your blog. But let me be honest, most of them are ugly. Though, you can still find great theme that you can use for free. My personal list of favorite places to get quality free themes:

  • WordPress.org Themes: The official repository for WordPress themes. Most are old and/or ugly, but there’s lots of beautiful, well coded free themes.
  • Smashing Magazine: The popular design blog offers very cool free themes from time to time.
  • Blog Oh Blog Themes: Quality themes, clean code.
  • ThemeLab: Lots of beautiful free themes.
  • SkinPress: A few cool themes to download and use freely.

Want even more free themes? 1st Web Designer compiled this list of 20 places to get free themes.

Also, note that several premium theme sellers distribute free themes from time to time. Please check out the list below for more info.

Premium themes


Although you can find good looking themes for free, lots of quality themes requires you to pay for it. A big pro of premium themes is that authors offer support, so you’ll have someone to help if needed.

  • Themeforest: Probably my favorite place to get quality themes for a cheap price. Hundreds of themes to choose from. Most themes have a clean code; however code quality may vary from a theme to another.
  • WooThemes: very popular premium theme seller. High quality design and code.
  • WP Zoom: High quality design, solid code, great support. Provide some free themes as well.
  • Elegant Themes: Beautiful themes, well coded. Pay once and get access to more than 80 themes.
  • Themify: Affordable themes with great design and quality.

Tutorials sites and blogs


When developing WordPress themes or plugins, you often need to refer to quality tutorials in order to learn new things or consolidate your knowledge. Below is my personal selection of interesting tutorial sites and blogs.

  • WP Tuts+: New articles almost everyday, always interesting.
  • Smashing Magazine: The popular design blog have some very in-depth tutorials and articles about WP.
  • Digging into WordPress: One of my favorites WordPress tutorials blog. Authored by Jeff Starr and Chris Coyier.
  • WP Engineer: Lots of coding tutorials, tip and tricks. A must read for WordPress enthusiasts.
  • WPMU: A multi-author site, with lots of new content every week.

I guess most of you know that here at CatsWhoCode, I often write lots of useful posts about WordPress, so don’t forget to bookmark the site if you haven’t done already!

Code snippets


Several websites and blogs are offering ready to use WordPress code snippets. Super useful when you need to achieve a particular task.

  • WPRecipes: Another site of mine, online since 2008, with over 450 WordPress code snippets, hacks and tricks.
  • CSS-Tricks snippets: Quality code snippets repository.
  • WP Mayor: Several interesting code snippets.
  • WP Snippets: One of my favorite online place when I’m looking for a hack or snippet.
  • Snipplr: Lots of user-submitted code snippets.

WordPress News

  • WordPress.org News: Indeed, the first place to have a look at when looking for WordPress news is the official site.
  • WP Candy: Popular WordPress site with tons of fresh news.
  • Weblog Tolls Collection: One of the oldest blogs about WordPress.
  • WPTopics: A news site which aggregate news from lots of interesting blogs.

sql query to delete orphaned post meta in your WordPress database

Just run the following query on your WordPress database to delete orphaned post meta. Don’t forget to replace the table prefix wp_ if your database is using another prefix.
And of course, create a backup of your database before running the query!

DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id
WHERE wp.ID IS NULL

Thanks to Patrick Rauland for submitting this useful recipe!

How to allow more HTML tags in WordPress comments

Simply paste the following code in your functions.php file. The list of tags to allow can be modified on line 4.

// Create function which allows more tags within comments
function allow_pres() {
  global $allowedtags;
  $allowedtags['pre'] = array('class'=>array());
}

// Add WordPress hook to use the function
add_action('comment_post', 'allow_pres');

Thanks to David Walsh for the handy tip!

HTML5 code snippets to take your website to the next level

Url and email input types

HTML5 introduced new input types url and email are one of those. They allow you to write a more semantically correct code and make the form completion easier on mobile devices, by displaying special buttons (like the @ or .com buttons) depending on the input type.

Here is the url attribute in action:

<input type="url" value="">

And the email attribute as well. Please also pay attention to the pattern attribute as I will explain it below.

<input type="email" pattern="[^ @]*@[^ @]*" value="">

Source: http://davidwalsh.name/html5-email

Regexp patterns for form validation

Before HTML5, when you used a form on your website, you had to use JavaScript to create a front-side validation. Now with HTML5 and the pattern attribute, you can define a regular expression pattern to validate the data.

The following snippet is for validating email addresses:

<input type="text" title="email" required pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" />

This one is for strong passwords:

<input title="at least eight symbols containing at least one number, one lower, and one upper letter" type="text" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" required />

And this one is for validating phone numbers:

<input type="text" required pattern="(\+?\d[- .]*){7,13}" title="international, national or local phone number"/>

Source: http://blog.staffannoteberg.com/2012/03/01/html5-form-validation-with-regex/

Context menus with HTML5

HTML5 context menus allows you to add elements to the contextual menu which appears when the user right click somewhere on your page.
At the time of writing this article, the contextmenu element is only compatible with Firefox, so let’s hope other browsers will implement it very soon.

<section contextmenu="mymenu"> 
<p>Yes, this section right here</p>
</section>

<menu type="context" id="mymenu">
  <menuitem label="Please do not steal our images" icon="img/forbidden.png"></menuitem>
  <menu label="Social Networks">
  <menuitem label="Share on Facebook" onclick="window.location.href = 'http://facebook.com/sharer/sharer.php?u=' + window.location.href;">   </menuitem>
  </menu>
</menu>

Source/Demo: http://speckyboy.com/2013/02/13/quick-tip-the-html5…

HTML5 video, with Flash fallback

One of the greatest new possibilities of HTML5 is definitely its ability to play video files without requesting the use of Flash. Though, as older browsers are not compatible with HTML5 videos, you should implement a Flash fallback. The following example show how to embed mp4 and ogv videos in HTML5, with a Flash fallback for older browsers.

<video width="640" height="360" controls>
	<source src="__VIDEO__.MP4"  type="video/mp4" />
	<source src="__VIDEO__.OGV"  type="video/ogg" />
	<object width="640" height="360" type="application/x-shockwave-flash" data="__FLASH__.SWF">
		<param name="movie" value="__FLASH__.SWF" />
		<param name="flashvars" value="controlbar=over&amp;image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
		<img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
		     title="No video playback capabilities, please download the video below" />
	</object>
</video>

Source: http://camendesign.com/code/video_for_everybody

Autocompletion with HTML5 datalists

Using the datalist element, HTML5 allows you to create a list of data to autocomplete an input field. Super useful!

<input name="frameworks" list="frameworks" />

<datalist id="frameworks">
	<option value="MooTools">
	<option value="Moobile">
	<option value="Dojo Toolkit">
	<option value="jQuery">
	<option value="YUI">
</datalist>

Source/Demo: http://davidwalsh.name/datalist

Hidden elements using HTML5

HTML5 introduce the hidden attribute, which allow you to hide a specific element, as you would do it in CSS using display:none.

<p hidden>You can't see this text</p>

Source: http://html5demos.com/hidden

element with autofocus

The autofocus attribute allow you to force the focus on a specific element. Useful for search pages such as google.com homepage.

<input autofocus="autofocus" />

Source: http://davidwalsh.name/autofocus

HTML5 prefetching

Some time ago I wrote a detailed article about HTML5 prefetching. Basically, prefetching is a simple technique to prefetch and load a resource which is not included in the current page.

The example below shows the prefetching of an image:

<link rel="prefetch" href="http://www.catswhocode.com/wp-content/uploads/my_image.png">

Source: http://www.catswhocode.com/blog/mastering-html5-prefetching

Playing audio files with HTML5

HTML5 can play videos as I shown you before, and of course it can also play audio files such as the popular mp3 format. As an example, here is a minimalist but functional audio player.

<audio id="player" src="sound.mp3"></audio>
<div>
	<button onclick="document.getElementById('player').play()">Play</button>
	<button onclick="document.getElementById('player').pause()">Pause</button>
	<button onclick="document.getElementById('player').volume+=0.1">Volume Up</button>
	<button onclick="document.getElementById('player').volume-=0.1">Volume Down</button>
</div> 

Source: http://www.catswhocode.com/blog/mastering-the-html5-audio-property

Grid Layout Shock giveaway: 10 licenses to win!

About Grid Layout Shock

Grid Layout Shock is a responsive WordPress plugin to create cool Pinterest-like grids using your posts, or external content (RSS). With several customization options to make every grid unique.

For more info about Grid Layout Shock, just have a look to the demo site: http://www.gridlayoutshock.com/

How to enter the giveaway?

It’s free, and it’s very simple: Just leave a comment on this post to join. In one week (Thursday March 7) 10 lucky winners will be randomly picked. They will receive their Grid Layout Shock license by email.

Now, good luck everyone!

WordPress function to show a total share counter (FB, Twitter, G+)

Simply paste the following function where you want your counter to appear:

function social_shares() {
    $url = get_permalink( $post_id ); 
    $json = file_get_contents(&quot;http://api.sharedcount.com/?url=" .
rawurlencode($url));
    $counts = json_decode($json, true);
    $totalcounts= $counts[&quot;Twitter&quot;] + 
$counts[&quot;Facebook&quot;][&quot;total_count&quot;] +
$counts[&quot;GooglePlusOne&quot;];
    echo &quot;&lt;div&gt;$totalcounts Share&lt;/div&gt;&quot;;
}

Thanks a lot to Davide for submitting this tip!

How to easily make WordPress images responsive

The first thing to do is to create the shortcode. To do so, open your functions.php file and paste the following code in it:

function responsive_images($atts, $content = null) {
     return '<div class="image-resized">' . $content .'</div>';
}
 
add_shortcode('responsive', 'responsive_images');

Once done, open your style.css file and add those CSS rules:

@media only screen and (max-width:767px) {
    .image-resized img {
        width:100%;
        height:auto;
    }
}

You can now use the [responsive] shortcode to insert responsive images in your blog:

[responsive]<img src="image_url" alt="alt" title="title" />[/responsive]

Thanks to Rockable Themes for the tip!

WordPress snippets, hacks and tips to enhance your comments section

Allow more HTML tags in WordPress comments

By default, WordPress allow commenters to use some HTML tags in the comment textarea. But depending on your blog, you might want to allow the use of more tags.

To do so, simply paste the code below into your functions.php file. The list of allowed tags can be modified on line 4.

// Create function which allows more tags within comments
function allow_pres() {
  global $allowedtags;
  $allowedtags['pre'] = array('class'=>array());
}

// Add WordPress hook to use the function
add_action('comment_post', 'allow_pres');

» Source: http://davidwalsh.name/wordpress-comment-tags

Remove autolinks in comments

When a commenter paste a url link into the comment form, WordPress automatically transform it into a hypertext link. This is good on most cases, but personally I do not like this as many people used my blog comments to advertise their own products and services.

Removing autolinks in comments is super easy: Just insert the line of code below into your functions.php file.

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

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

Remove the url field from WordPress comments form

If you don’t want your commenters to be able to enter their website url, here is a snippet to remove the url field from WordPress comment form.

Simple paste the code below in your functions.php file, save it, and you’re done.

function remove_comment_fields($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');

» Source: http://wp.tutsplus.com/tutorials/creative-coding/customizing-comments…

Add more fields to the comments form

I just shown you how to remove a field from the comment form, but now, what if you want to add a new field to the form? The following example will add a new field for the commenter to add his age.

Let’s start by adding the field. To do this, copy the code below and paste it in your functions.php file:

function add_comment_fields($fields) {
 
    $fields['age'] = '<p class="comment-form-age"><label for="age">' . __( 'Age' ) . '</label>' .
        '<input id="age" name="age" type="text" size="30" /></p>';
    return $fields;
 
}
add_filter('comment_form_default_fields','add_comment_fields');

function add_comment_meta_values($comment_id) {
 
    if(isset($_POST['age'])) {
        $age = wp_filter_nohtml_kses($_POST['age']);
        add_comment_meta($comment_id, 'age', $age, false);
    }
 
}
add_action ('comment_post', 'add_comment_meta_values', 1);

Now, to display the age of the commenter, use the following code:

<?php echo "Comment authors age: ".get_comment_meta( $comment->comment_ID, 'age', true ); ?>

» Source: http://wp.tutsplus.com/tutorials/creative-coding/customizing-comments…

Insert comments programatically

On some specific cases, you might want to insert comments programmatically. Doing so is definitely easy, as shown below. Simply execute this code and it will add a new comment in your database.

$data = array(
	'comment_post_ID' => 1,
	'comment_author' => 'admin',
	'comment_author_email' => '[email protected]',
	'comment_author_url' => 'http://www.catswhocode.com',
	'comment_content' => 'Lorem ipsum dolor sit amet...',
	'comment_author_IP' => '127.0.0.1',
	'comment_agent' => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; fr; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3',
	'comment_date' => date('Y-m-d H:i:s'),
	'comment_date_gmt' => date('Y-m-d H:i:s'),
	'comment_approved' => 1,
);

$comment_id = wp_insert_comment($data);

» Source: http://www.wprecipes.com/wordpress-hack-insert-comments-programatically

Automatically disable commenting on posts older than X days

If your blog is very popular, you probably receive lots of comments, some on very old posts… So why not automatically disable commenting on posts older than X days?

Paste the code below in your functions.php file. The code will disable comments on post older than 30 days. The amount of days can be changed on line 3.

function close_comments( $posts ) {
	if ( !is_single() ) { return $posts; }
	if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( 30 * 24 * 60 * 60 ) ) {
		$posts[0]->comment_status = 'closed';
		$posts[0]->ping_status    = 'closed';
	}
	return $posts;
}
add_filter( 'the_posts', 'close_comments' ); 

» Source: http://perishablepress.com/wordpress-tip-disable-comments-in-old-posts-via-php/

Add target=”blank” to all links in comment text

Using the HTML target="blank" attribute is generally discouraged as this force the opening of a link in a new tab or window, but I know how clients like it. So if you need to add a target="blank" attribute to every links in comments text, just paste the code shown below in your functions.php and you’ll get the job done.

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

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

Customize comments markup

By default, WordPress outputs a standard comments list, but if can be customized if needed. Paste the following code into your functions.php file and customize as desired.

function my_custom_comments($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; ?>
   <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
   <?php if ($comment->comment_approved == '0') : ?>
      <em><?php _e('Your comment is awaiting moderation.') ?></em>
   <?php endif; ?>

   // Comments markup code here, e.g. functions like comment_text(); 

}

Once done, use the following line of code in comments.php to display your custom comment markup:

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

» Source: http://css-tricks.com/snippets/wordpress/customize-comments-markup/

Disable comments feeds in individual posts

By default, WordPress create RSS feeds for all individual posts. If you don’t want or need them, you can disable them with the following code snippet. Simply paste it in your functions.php file and you’ll get rid of individual post feeds.

// disable comment feeds for individual posts
function disablePostCommentsFeedLink($for_comments) {
	return;
}
add_filter('post_comments_feed_link','disablePostCommentsFeedLink');

» Source: http://digwp.com/2009/11/disable-comment-feeds-individual-posts/

Want more WordPress tips and snippets? Then have a look to WPRecipes, another blog of mine!

SQL query to turn categories into tags (and vice versa)

Just run the following query on your WordPress database, and all categories will be turned into tags. Don’t forget to replace the table prefix wp_ if your database is using another prefix.
And of course, do not forget to make a backup of your database before running the query!

UPDATE wp_term_taxonomy SET taxonomy='post_tag', parent=0 WHERE taxonomy='category';

Thanks to Go WordPress for the tip!

How to exclude specific categories from your blog homepage

Copy the snippet below in your functions.php file. Replace the category IDs on line 3 with the ones you want to exclude. Then save the file and you’re done.

function exclude_category_home( $query ) {
    if ( $query->is_home ) {
        $query->set( 'cat', '-5, -34' );
    }
    return $query;
}
 
add_filter( 'pre_get_posts', 'exclude_category_home' );

Thanks to WP Mayor for the code snippet!