WordPress tip: Check whether a plugin is active

Just paste the code below in your theme file, wherever you’d like to check out if a plugin is activated or not. Update the code with the plugin directory and name on line 4.

<?php 
   include_once( ABSPATH . 'wp-admin/includes/plugin.php' );

   if(is_plugin_active('plugin-directory/plugin-file.php')) {
      //plugin is activated
   }
?>

Thanks to Jean galea for this brillant tip!

Mighty Deals giveaway: $150 of prizes to win

A word about Mighty Deals

MightyDeals.com offers unbelievable deals and discounts for creative professionals. The deals include products and services that are heavily discounted, exclusively for Mighty Deals customers, usually from 50% to 90% off.
Each deal stays on the site for a very limited time so if you want to make sure you never miss a great deal, we recommend going to their site and subscribing.

Prizes to win

Choose any prize you want, up to $50.

How to enter the giveaway

Joining the giveaway is 100% free and super simple: The only thing you have to do is to leave a comment on this post to let me know which prize you’d like to win. You can pick any prize you want up to $50.

In one week (on monday 15th of July) I’ll randomly pick 3 winners using random.org. Winners will directly receive their prize by email from Mighty Deals staff.

Now, good luck everyone!

WordPress tip: Force specific pages to be SSL secure

Just add the following snippet to the functions.php file of your WordPress theme and specify the post or page ID desired.

function wps_force_ssl( $force_ssl, $post_id = 0, $url = '' ) {
    if ( $post_id == 25 ) {
        return true
    }
    return $force_ssl;
}
add_filter('force_ssl' , 'wps_force_ssl', 10, 3);

Thanks to Kevin Chard for this recipe!

How to crop uploaded images instead of scaling them

Just add the code below to your functions.php file:

// Standard Size Thumbnail
if(false === get_option("thumbnail_crop")) {
     add_option("thumbnail_crop", "1"); }
     else {
          update_option("thumbnail_crop", "1");
     }

// Medium Size Thumbnail
if(false === get_option("medium_crop")) {
     add_option("medium_crop", "1"); }
     else {
          update_option("medium_crop", "1");
     }

// Large Size Thumbnail
if(false === get_option("large_crop")) {
     add_option("large_crop", "1"); }
     else {
          update_option("large_crop", "1");
      }

Thanks to wp-snippet.com for the tip!

WordPress shortcode to embed Google trends graphs

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

function wps_trend($atts){
        extract( shortcode_atts( array(
                'w' => '500',           // width
                'h' => '330',           // height
                'q' => '',              // query
                'geo' => 'US',          // geolocation
        ), $atts ) );
        //format input
        $h=(int)$h;
        $w=(int)$w;
        $q=esc_attr($q);
        $geo=esc_attr($geo);
         ob_start();
?>
<script type="text/javascript" src="http://www.google.com/trends/embed.js?hl=en-US&q=<?php echo $q;?>&geo=<?php echo $geo;?>&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=<?php echo $w;?>&h=<?php echo $h;?>"></script>
<?php
return ob_get_clean();
}
add_shortcode("trends","wps_trend");

Once you saved your functions.php file, you can now use the shortocode in your posts and pages. Here is an example of usage:

[trends h="450" w="500" q="wpsnipp,wordpress,+wordpress+theme,+wordpress+plugin,+wordpress+snippets" geo="US"]

Thanks to Kevin Chard for the shortcode!

How to setup different admin and theme languages on your WordPress blog

Simply set the desired locale (on line 6) then add the code to your functions.php file.

<?php
     // setup one language for admin and the other for theme
     // must be called before load_theme_textdomain()

     function set_my_locale($locale) {
          $locale = ( is_admin() ) ? "en_US" : "it_IT";
          setlocale(LC_ALL, $local );
          return $locale;
     }
     add_filter( 'locale', 'set_my_locale' );
?>

Thanks to wp-snippet for the cool tip!

Useful jQuery code snippets

Smooth scrolling to #anchor

On your site footer, it is very useful to provide a quick way for your visitors to scroll back to the top of the page. Here is a simple way to smooth scroll to a #anchor of your choice.

// HTML:
// <h1 id="anchor">Lorem Ipsum</h1>
// <p><a href="#anchor" class="topLink">Back to Top</a></p>


$(document).ready(function() {

	$("a.topLink").click(function() {
		$("html, body").animate({
			scrollTop: $($(this).attr("href")).offset().top + "px"
		}, {
			duration: 500,
			easing: "swing"
		});
		return false;
	});

});

Source: http://snipplr.com/view/26739/jquery–smooth-scroll-to-anchor/

Image resizing using jQuery

Although you should resize your images on server side (using PHP and GD for example) it can be useful to be able to resize images using jQuery. Here’s a handy code snippet to do it.

$(window).bind("load", function() {
	// IMAGE RESIZE
	$('#product_cat_list img').each(function() {
		var maxWidth = 120;
		var maxHeight = 120;
		var ratio = 0;
		var width = $(this).width();
		var height = $(this).height();
	
		if(width > maxWidth){
			ratio = maxWidth / width;
			$(this).css("width", maxWidth);
			$(this).css("height", height * ratio);
			height = height * ratio;
		}
		var width = $(this).width();
		var height = $(this).height();
		if(height > maxHeight){
			ratio = maxHeight / height;
			$(this).css("height", maxHeight);
			$(this).css("width", width * ratio);
			width = width * ratio;
		}
	});
	//$("#contentpage img").show();
	// IMAGE RESIZE
});

Source: http://snipplr.com/view/62552/mage-resize/

Load content on scroll automatically

Some websites such as Twitter loads content on scroll. Which means that all content is dynamically loaded on a single page as long as you scroll down.

Here’s how you can replicate this effect on your website:

var loading = false;
$(window).scroll(function(){
	if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){
		if(loading == false){
			loading = true;
			$('#loadingbar').css("display","block");
			$.get("load.php?start="+$('#loaded_max').val(), function(loaded){
				$('body').append(loaded);
				$('#loaded_max').val(parseInt($('#loaded_max').val())+50);
				$('#loadingbar').css("display","none");
				loading = false;
			});
		}
	}
});

$(document).ready(function() {
	$('#loaded_max').val(50);
});

Source: http://fatfolderdesign.com/173/content-load-on-scroll-with-jquery

Test Password Strength

When building forms, it’s a very good practice to provide verifications on the front-end first so the visitor do not have to submit the form endlessly to correct problems. This code snippet is using regular expressions to test if a password is strong enough. Of course, don’t forget to validate your forms on the server side as well!

$('#pass').keyup(function(e) {
     var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
     var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
     var enoughRegex = new RegExp("(?=.{6,}).*", "g");
     if (false == enoughRegex.test($(this).val())) {
             $('#passstrength').html('More Characters');
     } else if (strongRegex.test($(this).val())) {
             $('#passstrength').className = 'ok';
             $('#passstrength').html('Strong!');
     } else if (mediumRegex.test($(this).val())) {
             $('#passstrength').className = 'alert';
             $('#passstrength').html('Medium!');
     } else {
             $('#passstrength').className = 'error';
             $('#passstrength').html('Weak!');
     }
     return true;
});

Source: http://css-tricks.com/snippets/jquery/password-strength/

Equalize heights of div elements

Equalizing heights of div elements is not possible (or very hacky) to do in pure CSS, so jQuery is here to help. The code below will automatically adjust the heights of div elements according to the higher one.

var maxHeight = 0;

$("div").each(function(){
   if ($(this).height() > maxHeight) { maxHeight = $(this).height(); }
});

$("div").height(maxHeight);

Source: http://css-tricks.com/snippets/jquery/equalize-heights-of-divs/

Simple and efficient png fix for IE6

In 2013, IE6 is finally almost gone and people are using newer browsers. But still, in some situations you have to care about this horrible browser and provide a IE6-compliant website. As IE6 can’t deal with png transparency, here’s a super simple jQuery hack to force png rendering.

Just add a .pngfix class to anything you want fixed or put in some other jQuery selector.

$('.pngfix').each( function() {
   $(this).attr('writing-mode', 'tb-rl');
   $(this).css('background-image', 'none');
   $(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="scale")');
});

Source: http://itknowledgeexchange.techtarget.com/itanswers/

Parsing json with jQuery

Parsing json data with jQuery is not complicated at all. Here is an efficient example on how to parse json data and append it to your web page.

function parseJson(){
	//Start by calling the json object, I will be using a 
        //file from my own site for the tutorial 
	//Then we declare a callback function to process the data
	$.getJSON('hcj.json',getPosts);
 
	//The process function, I am going to get the title, 
        //url and excerpt for 5 latest posts
	function getPosts(data){
 
		//Start a for loop with a limit of 5 
		for(var i = 0; i < 5; i++){
			//Build a template string of 
                        //the post title, url and excerpt
			var strPost = '<h2>' 
				      + data.posts[i].title
				      + '</h2>'
				      + '<p>'
				      + data.posts[i].excerpt
				      + '</p>'
				      + '<a href="'
				      + data.posts[i].url
				      + '" title="Read '
				      + data.posts[i].title
				      + '">Read ></a>';
 
			//Append the body with the string
			$('body').append(strPost);
 
		}
	}
 
}
 
//Fire off the function in your document ready
$(document).ready(function(){
	parseJson();				   
});

Source: http://hankchizljaw.co.uk/tutorials/parse-json-with-jquery-snippet/06/05/2012/

Alternating Row Colors

On big lists or tables, alternating row colors can drastically improve readability. Here’s how to alternate row colors on a list of elements using some jQuery. You can use any HTML element you like, td, tr, li, etc…

//jquery
  $('div:odd').css("background-color", "#F4F4F8");
  $('div:even').css("background-color", "#EFF1F1");


//html example
<div>Row 1</div>
<div>Row 2</div>
<div>Row 3</div>
<div>Row 4</div>

Facebook like image preloader

Ever noticed how fast images load when paging through a Facebook photo album? This is because Facebook is preloading each of these images into your browser’s cache before you even view them. Here’s how you can achieve a similar behavior on your website using some jQuery magic.

var nextimage = "/images/some-image.jpg";
$(document).ready(function(){
window.setTimeout(function(){
var img = $("<img>").attr("src", nextimage).load(function(){
//all done
});
}, 100);
});

Source: http://www.nealgrosskopf.com/tech/thread.php?pid=77

Make entire div clickable

Here’s an easy way to make the parent div of a link clickable. Let’s say you have this html code:

<div class="myBox">
     blah blah blah.
    <a href="http://google.com">link</a>
</div>

The following lines of jQuery will make the entire div clickable:

$(".myBox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
});

Source: http://css-tricks.com/snippets/jquery/make-entire-div-clickable/

WordPress hacks and snippets to efficiently reduce spam

Automatically mark as spam comments with a super long url

Have you ever noticed that most spam comments have a very long url? So a good way to catch more spam comments which haven’t been caught by Akismet is to automatically mark as spam comments with an url longer than 50 characters.

To apply this tip, just paste the code below in your functions.php file. This code will mark as spam any comment with an url longer than 50 characters. This number can be changed on line 4.

<?php

  function rkv_url_spamcheck( $approved , $commentdata ) {
    return ( strlen( $commentdata['comment_author_url'] ) > 50 ) ? 'spam' : $approved;
  }

  add_filter( 'pre_comment_approved', 'rkv_url_spamcheck', 99, 2 );

?>

This snippet is really efficient and allowed me to reduce spam on my blogs.

Source: http://css-tricks.com/snippets/wordpress/spam-comments-with-very-long-urls/

Remove the url field from your comment form

A radical way to fight spam on your blog is to remove the url field from your comment form, so commenters will not be able to link to their website. It’s not really cool for them, but if you’re running a very large blog with lots of spam, this can be a solution.

Paste this code into your functions.php file. Once saved, the url field will be removed from your comment form.

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-in-wordpress…/

Remove url field from the comment form and automatically spam comments with urls

Now if you want a really really efficient and radical way to get rid of spam, let combine the two functions above.

First, let’s remove the url field from the comment form. And then, make sure that no spammer have a trick to still inserting an url by automatically mark as spam any comment with something in the url field.

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

<?php

  function rkv_url_spamcheck( $approved , $commentdata ) {
    return ( strlen( $commentdata['comment_author_url'] ) > 1 ) ? 'spam' : $approved;
  }

  add_filter( 'pre_comment_approved', 'rkv_url_spamcheck', 99, 2 );

?>

This code have to be pasted in your functions.php file to work.

Unlink urls in comment text

Are you tired that some people use your website to link to other sources, most of them being unrelated to the post content? Then here’s a trick I’m using on both CatsWhoCode.com and WPRecipes.com: Remove the automatic linking of url in the comment text.

As usual, this code goes straight to your functions.php file.

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

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

Automatic “Nofollow” for external links in comment text

If you want to reduce the amount of spammy links in comment text, without removing the automatic linking of urls as shown above, here’s an alternative: Simply add a rel="nofollow" attribute to all external links.

Paste the code below into your functions.php file, and then save the file.

add_filter('comment_text', 'auto_nofollow');
 
function auto_nofollow($content) {
    //return stripslashes(wp_rel_nofollow($content));
 
    return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
}
 
function auto_nofollow_callback($matches) {
    $link = $matches[0];
    $site_link = get_bloginfo('url');
 
    if (strpos($link, 'rel') === false) {
        $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);
    } elseif (preg_match("%href=S(?!$site_link)%i", $link)) {
        $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);
    }
    return $link;
}

Source: http://www.onextrapixel.com/2012/10/12/5-code-snippets-for-interacting…

Spam comments based on a word list

As spammers generally target specific keywords, it can be useful to create a blacklist and automatically mark as spam comments which contains one or more words from the blacklist.

To add keywords, simply edit the array on line 9. Then, paste this code snippet into your functions.php file.

function in_comment_post_like($string, $array) { 
	foreach($array as $ref) { if(strstr($string, $ref)) { return true; } } 
	return false;
}
function drop_bad_comments() {
	if (!empty($_POST['comment'])) {
		$post_comment_content = $_POST['comment'];
		$lower_case_comment = strtolower($_POST['comment']);
		$bad_comment_content = array(
			'viagra', 
			'hydrocodone',
			'hair loss',
			'[url=http', 
			'[link=http', 
			'xanax',
			'tramadol',
			'russian girls',
			'russian brides',
			'lorazepam',
			'adderall',
			'dexadrine',
			'no prescription',
			'oxycontin',
			'without a prescription',
			'sex pics',
			'family incest',
			'online casinos',
			'online dating',
			'cialis',
			'best forex',
			'amoxicillin'
		);
		if (in_comment_post_like($lower_case_comment, $bad_comment_content)) {
			$comment_box_text = wordwrap(trim($post_comment_content), 80, "\n  ", true);
			$txtdrop = fopen('/var/log/httpd/wp_post-logger/nullamatix.com-text-area_dropped.txt', 'a');
			fwrite($txtdrop, "  --------------\n  [COMMENT] = " . $post_comment_content . "\n  --------------\n");
			fwrite($txtdrop, "  [SOURCE_IP] = " . $_SERVER['REMOTE_ADDR'] . " @ " . date("F j, Y, g:i a") . "\n");
			fwrite($txtdrop, "  [USERAGENT] = " . $_SERVER['HTTP_USER_AGENT'] . "\n");
			fwrite($txtdrop, "  [REFERER  ] = " . $_SERVER['HTTP_REFERER'] . "\n");
			fwrite($txtdrop, "  [FILE_NAME] = " . $_SERVER['SCRIPT_NAME'] . " - [REQ_URI] = " . $_SERVER['REQUEST_URI'] . "\n");
			fwrite($txtdrop, '--------------**********------------------'."\n");
			header("HTTP/1.1 406 Not Acceptable");
			header("Status: 406 Not Acceptable");
			header("Connection: Close");
			wp_die( __('bang bang.') );
		}
	}
}
add_action('init', 'drop_bad_comments');

Source: http://www.wprecipes.com/automatically-refuse-spam-comments-on-your-wordpress-blog

Deny commenting to non-referrer requests

Here is a very useful tip to prevent spambots from dropping spam bombs by denying access to all requests that do not originate from your domain.

Copy the code below, update the domain name on line 5 and then paste it in your .htaccess file. This file is located at the root of your WordPress install. Don’t forget to always make a backup before editing this file!

# block comment spam by denying access to no-referrer requests
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*catswhocode.com.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule ^(.*)$ ^http://the-site-where-you-want-to-send-spammers.com/$ [R=301,L]

Source: http://perishablepress.com/block-spam-by-denying-access-to-no-referrer-requests/

Automatically link Twitter usernames in WordPress

Paste the code below into your functions.php file:

function twtreplace($content) {
	$twtreplace = preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/',"$1<a href=\"http://twitter.com/$2\" target=\"_blank\" rel=\"nofollow\">@$2</a>",$content);
	return $twtreplace;
}

add_filter('the_content', 'twtreplace');   
add_filter('comment_text', 'twtreplace');

Once you saved the file all twitter usernames in posts and comments will automatically be linked to their Twitter profiles. Usernames have to be written under the form @username.

Thanks to ederwp for the tip!

10 awesome PHP functions and snippets

Sanitize database inputs

When inserting data in your database, you have to be really careful about SQL injections and other attempts to insert malicious data into the db. The function below is probably the most complete and efficient way to sanitize a string before using it with your database.

function cleanInput($input) {

  $search = array(
    '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
  );

    $output = preg_replace($search, '', $input);
    return $output;
  }
?>
<?php
function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        }
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    }
    return $output;
}

Here’s some examples of use:

<?php
  $bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

  // Also use for getting POST/GET variables
  $_POST = sanitize($_POST);
  $_GET  = sanitize($_GET);
?>

Source: http://css-tricks.com/snippets/php/sanitize-database-inputs/

Calculate distance between two points

Want to be able to calculate the distance between two points? The function below use the latitude and longitude of two locations, and calculate the distance between them in both miles and metric units.

function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $feet = $miles * 5280;
    $yards = $feet / 3;
    $kilometers = $miles * 1.609344;
    $meters = $kilometers * 1000;
    return compact('miles','feet','yards','kilometers','meters'); 
}

Example:

$point1 = array('lat' => 40.770623, 'long' => -73.964367);
$point2 = array('lat' => 40.758224, 'long' => -73.917404);
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
foreach ($distance as $unit => $value) {
    echo $unit.': '.number_format($value,4).'<br />';
}

Source: http://www.inkplant.com/code/calculate-the-distance-between-two-points.php

Get all tweets of a specific hashtag

Here’s a quick and easy way to get all tweets of a specific usage using the useful cURL library. The following example will retrieve all tweets with the #cat hashtag.

function getTweets($hash_tag) {

    $url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ;
    echo "<p>Connecting to <strong>$url</strong> ...</p>";
    $ch = curl_init($url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $xml = curl_exec ($ch);
    curl_close ($ch);

    //If you want to see the response from Twitter, uncomment this next part out:
    //echo "<p>Response:</p>";
    //echo "<pre>".htmlspecialchars($xml)."</pre>";

    $affected = 0;
    $twelement = new SimpleXMLElement($xml);
    foreach ($twelement->entry as $entry) {
        $text = trim($entry->title);
        $author = trim($entry->author->name);
        $time = strtotime($entry->published);
        $id = $entry->id;
        echo "<p>Tweet from ".$author.": <strong>".$text."</strong>  <em>Posted ".date('n/j/y g:i a',$time)."</em></p>";
    }

    return true ;
}

getTweets('#cats');

Source: http://www.inkplant.com/code/get-twitter-posts-by-hashtag.php

Applying Even/Odd Classes

When generating lists or tables using php, it is super useful to apply even/odd classes to each row of data in order to simplify CSS styling.

Used inside a loop, class names would be named .example-class0 and .example-class1 alternating. Increasing the “2″ number allows you to increment in thirds or fourths or whatever you need:

<div class="example-class<?php echo ($xyz++%2); ?>">

Source: http://css-tricks.com/snippets/php/applying-evenodd-classes/

Email error logs to yourself

Instead of publicly displaying possible errors on your website, why not using a custom error handler to email error logs to yourself? Here’s a handy code snippet to do it.

<?php

// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars){
	$email = "
		<p>An error ($number) occurred on line 
		<strong>$line</strong> and in the <strong>file: $file.</strong> 
		<p> $message </p>";
		
	$email .= "<pre>" . print_r($vars, 1) . "</pre>";
	
	$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
	
	// Email the error to someone...
	error_log($email, 1, '[email protected]', $headers);

	// Make sure that you decide how to respond to errors (on the user's side)
	// Either echo an error message, or kill the entire project. Up to you...
	// The code below ensures that we only "die" if the error was more than
	// just a NOTICE. 
	if ( ($number !== E_NOTICE) && ($number < 2048) ) {
		die("There was an error. Please try again later.");
	}
}

// We should use our custom function to handle errors.
set_error_handler('nettuts_error_handler');

// Trigger an error... (var doesn't exist)
echo $somevarthatdoesnotexist;

Source: http://net.tutsplus.com/tutorials/php/quick-tip-email-error-logs-to-yourself-with-php/

Automatically creates variables with the same name as the key in the POST array

This snippet is very helpful for every POST processing. All you need is an array with expected keys in the POST array. This snippet automatically creates variables with the same name as the key in the POST array. If the key is not found in the POST array the variable is set to NULL. Basically you dont need to write:

$username=$_POST["username"];
$age=$_POST["age"];
etc.

This snippet will do this boring part of every PHP code with POST handling so you can fully focus on a validation of the input, because that is much more important.

<?php
$expected=array('username','age','city','street');
foreach($expected as $key){
    if(!empty($_POST[$key])){
        ${key}=$_POST[$key];
    }
    else{
        ${key}=NULL;
    }
}
?>

Source: http://www.catswhocode.com/blog/snippets/automatically-creates-variables…

Download & save a remote image on your server using PHP

Here’s a super easy and efficient way to download a remote image and save it on your own server.

$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //save the image on your server

Source: http://www.catswhocode.com/blog/snippets/download-save-a-remote-image…

Create data uri’s

Data uri’s can be useful for embedding images into HTML/CSS/JS to save on HTTP requests, at the cost of maintainability. You can use online tools to create data uri’s, or you can use the simple PHP function below:

function data_uri($file, $mime) {
  $contents=file_get_contents($file);
  $base64=base64_encode($contents);
  echo "data:$mime;base64,$base64";
}

Source: http://css-tricks.com/snippets/php/create-data-uris/

Detect browser language

When developing a multilingual website, I really like to retrieve the browser language and use this language as the default language for my website. Here’s how I get the language used by the client browser:

function get_client_language($availableLanguages, $default='en'){
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

		foreach ($langs as $value){
			$choice=substr($value,0,2);
			if(in_array($choice, $availableLanguages)){
				return $choice;
			}
		}
	} 
	return $default;
}

Source: http://snipplr.com/view/12631/detect-browser-language/php-detect-browser-language

Add (th, st, nd, rd, th) to the end of a number

This simple and easy function will take a number and add “th, st, nd, rd, th” after it. Very useful!

function ordinal($cdnl){ 
    $test_c = abs($cdnl) % 10; 
    $ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th' 
            : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1) 
            ? 'th' : 'st' : 'nd' : 'rd' : 'th')); 
    return $cdnl.$ext; 
}  
for($i=1;$i<100;$i++){ 
    echo ordinal($i).'<br>'; 
} 

Source: http://phpsnips.com/snip-37

Themes4all giveaway: LOTS of prizes to win!!

A word about Themes4All

Our sponsor is Themes4All.com, which is a newcomer in the WordPress premium theme business. They specialize in low cost/high quality themes.
They already released 20+ themes, each priced $10. Click here to view the available themes.

How to join the giveaway?

Joining the giveaway is super easy and free as usual. First, go to Themes4All.com and create a free account. Registration grant you access to a free theme each month. Once done, simply leave a comment on this post to join.
In two weeks (June 7, 2013) I’ll pick 5 winners using random.org.

Winners will get:
1. 4 template of your choice + premium beta responsive parallax slider
2. 3 template of your choice + premium beta responsive parallax slider
3. 2 template of your choice + premium beta responsive parallax slider
4. 1 template of your choice + premium beta responsive parallax slider
5. premium beta responsive parallax slider

If you won, you’ll receive your prize by email, directly by Themes4All staff. Now, good luck everyone!

How to automatically insert a list of related articles below the post

First, paste the code below into the functions.php file from your theme.

// "More from This Category" list by Bar?? Ünver @ Wptuts+
function wptuts_more_from_cat( $title = "More From This Category:" ) {
    global $post;
    // We should get the first category of the post
    $categories = get_the_category( $post->ID );
    $first_cat = $categories[0]->cat_ID;
    // Let's start the $output by displaying the title and opening the <ul>
    $output = '<div id="more-from-cat"><h3>' . $title . '</h3>';
    // The arguments of the post list!
    $args = array(
        // It should be in the first category of our post:
        'category__in' => array( $first_cat ),
        // Our post should NOT be in the list:
        'post__not_in' => array( $post->ID ),
        // ...And it should fetch 5 posts - you can change this number if you like:
        'posts_per_page' => 5
    );
    // The get_posts() function
    $posts = get_posts( $args );
    if( $posts ) {
        $output .= '<ul>';
        // Let's start the loop!
        foreach( $posts as $post ) {
            setup_postdata( $post );
            $post_title = get_the_title();
            $permalink = get_permalink();
            $output .= '<li><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></li>';
        }
        $output .= '</ul>';
    } else {
        // If there are no posts, we should return something, too!
        $output .= '<p>Sorry, this category has just one post and you just read it!</p>';
    }
    // Let's close the <div> and return the $output:
    $output .= '</div>';
    return $output;
}

Once done, open your single.php file and call the function as shown below, where you’d like to display the related posts:

<?php echo wptuts_more_from_cat( 'More From This Category:' ); ?>

Thanks to WP Tuts for the cool tip!

How to add nofollow attributes to all links in a specific category

Simply copy the code below and paste it on your functions.php file. Don’t forget to set the desired category ID on line 3.

function nofollow_cat_posts($text) {
global $post;
        if( in_category(1) ) { // SET CATEGORY ID HERE
                $text = stripslashes(wp_rel_nofollow($text));
        }
        return $text;
}
add_filter('the_content', 'nofollow_cat_posts');

Thanks to Sagive for submitting this function!

Automatically spam comments with a very long url

Open your functions.php file and paste the code below in it. This code will automatically mark as spam all comments with an url longer than 50 chars. This can be changed on line 4.

<?php

  function rkv_url_spamcheck( $approved , $commentdata ) {
    return ( strlen( $commentdata['comment_author_url'] ) > 50 ) ? 'spam' : $approved;
  }

  add_filter( 'pre_comment_approved', 'rkv_url_spamcheck', 99, 2 );

?>

Thanks to CSS Tricks for the code snippet!