Best WordPress snippets, hacks and tips from 2013

How to crop uploaded images instead of scaling them

Would you like to crop your thumbnails instead of scaling them? If yes, I have a very handy snippet for you today. Just read on and enjoy!

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");
      }

Source: http://wp-snippet.com/snippets/activate-cropping-for-all-thumbnail-sizes/

Automatically link Twitter usernames in WordPress

Are you using Twitter a lot? Today’s recipe is a cool piece of code to automatically link Twitter usernames on your posts, pages, and comments.

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');

Source: http://snipplr.com/view/70977/automatically-link-twitter…

Automatically spam comments with a very long url

Spam is definitely a problem for bloggers and most of you probably receive more than 100 spam comments per hour. Here is a simple recipe to automatically mark as spam all comments with an url longer than 50 characters.

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.

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 );

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

How to clean up wp_head() without a plugin

WordPress adds a lot of stuff through wp_head() hook included in most WordPress themes. Some of this stuff is useful, but some other isn’t. Here’s a quick recipe to clean up the wp_head() easily without using a plugin.

Paste the following lines of code into your functions.php file:

remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'start_post_rel_link' );
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'adjacent_posts_rel_link' );
remove_action( 'wp_head', 'wp_shortlink_wp_head' );

Source: http://www.themelab.com/remove-code-wordpress-header/

WordPress tip: Force specific pages to be SSL secure

If SSL is enabled on your webserver, you should definitely use it to protect your blog. Activating SSL on your specific pages on a WordPress blog is definitely easy: Just read on.

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);

Source: http://wpsnipp.com/index.php/functions-php/force-specific-pages…

How to run the loop outside of WordPress

Ever needed to be able to access your WordPress data and run a loop OUTSIDE of your WP install? Here’s a code snippet which allow you to run a WordPress loop on any PHP file, even outside of your WordPress install.

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('posts_per_page=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; ?>

Source: http://css-tricks.com/snippets/wordpress/run-a-loop-outside-of-wordpress/

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

Sharedcount.com is a useful website which allow you to get the total likes, shares, tweets, etc for a specific web page. Here’s a super handy function to display how many times a page has been liked/shared/tweeted on your blog.

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;;
}

Source: http://www.wprecipes.com/wordpress-function-to-show-a-total-share-counter-fb-twitter-g

How to easily make WordPress images responsive

Responsive images can be big on wide screens and automatically adapt to smaller screens such as iPad. Making your images responsive is not difficult to do: Here is a simple recipe to achieve it on your blog.

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]

Source: http://rockablethemes.com/wordpress-responsive-images/

How to add custom text to WordPress login page

If for some reason you need to display a custom message on WordPress login page, here is a quick and easy recipe to do it.

Nothing complicated, paste the code below in your functions.php file. Message can be customized on line 3.

function wps_login_message( $message ) {
    if ( empty($message) ){
        return "<p class='message'>Welcome to this site. Please log in to continue</p>";
    } else {
        return $message;
    }
}
add_filter( 'login_message', 'wps_login_message' );

Source: http://wpsnippy.com/2013/08/how-to-add-custom-text-to…

WordPress shortcode to embed Google trends graphs

Google trends is a service which allow you to track the popularity of specific keywords. Here’s the code to create a WordPress shortcode that will embed a Google trends graph of any comma separated query on your blog.

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");

Source: http://wpsnipp.com/index.php/functions-php/shortcode-embed-google-trends-graph…

How to bring back single-column dashboard in WordPress 3.8

Bringing back the single-column dashboard in WordPress 3.8 is pretty easy: just add this code to your theme’s functions.php file.

// force one-column dashboard
function shapeSpace_screen_layout_columns($columns) {
	$columns['dashboard'] = 1;
	return $columns;
}
add_filter('screen_layout_columns', 'shapeSpace_screen_layout_columns');

function shapeSpace_screen_layout_dashboard() { return 1; }
add_filter('get_user_option_screen_layout_dashboard', 'shapeSpace_screen_layout_dashboard');

Thanks to Jeff Starr for the tip!

Christmas giveaway: $500 worth of services from CodeInWP

A word about CodeInWP

Do you have a design but no time to develop it into a WordPress theme? Do you’d love a custom plugin to fit specific needs but have no clue how to do it? Then you need help from CodeInWP.

CodeInWP

CodeInWP is a small team of efficient developers focusing on the creation of high-quality and cost-effective WordPress themes. They work with the latest standards and guidelines, so your theme is 100% clean, fast and up to date. Just give them your psd file, and CodeInWP will do the rest. They also develop WordPress plugins on demand.

How to enter the giveaway

Entering this Christmas giveaway is free and super simple: Just leave a comment on this post to let me know you’re in. On Christmas day, I’ll randomly pick 5 lucky winners who’ll receive a $100 voucher for either psd to WP or WordPress development(customizations, plugins) jobs from CodeInWP.

Now, good luck and merry christmas from CatsWhoCode and CodeInWP!

Christmas contest: $400 worth of giveaway from Codemyconcept

A word about CodeMyConcept

Codemyconcept is a professional service put together by a team of programmers who specialize in psd to html coding.

This comes as a great solution for the artist community of the web building branch, who can now focus their talents on design, and leave the markup crafting to the code experts. It basically means that you just send them your website designs, fresh out of Photoshop (or Fireworks, Illustrator) and they transform it in a quality HTML5/CSS3 code in a couple of days.

Their team can also help you with WordPress implementation, newsletter template coding and responsive websites. Their prices are very competitive: $99 for a main page, and $79 for subsequent pages. For long term collaborations, they have partnership offers as well. The service is one of the most professional: their team is fast, reliable, and always using manually typed code.

How to join the contest?


In order to join the contest, all you have to do is leave a comment below and let me know how you will use the money prize. The two winners will be randomly selected from all the users who commented.

This giveaway ends on December 16, 2013, after which the comments section on this post will be closed. Please leave a valid email address when filling out the comment form so that you can be contacted should you win. The winners will be contacted by email directly by codemyconcept. Please note that comments are moderated and your comment may not show up right away. Those comments that don’t conform to the posting conditions may be removed or not published.

7 little known but super useful PHP functions

highlight_string()

When displaying PHP code on a website, the highlight_string() function can be really helpful: It outputs or returns a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP.

Usage:

<?php
highlight_string('<?php phpinfo(); ?>');
?>

Documentation: http://php.net/manual/en/function.highlight-string.php

str_word_count()

This handy function takes a string as a parameter and return the count of words, as shown in the example below.

Usage:

?php
$str = "How many words do I have?";
echo str_word_count($str); //Outputs 5
?>

Documentation: http://php.net/manual/en/function.str-word-count.php

levenshtein()

Ever find the need to determine how different (or similar) two words are? Then levenshtein() is just the function you need. This function can be super useful to track user submitted typos.

Usage:

<?php
$str1 = "carrot";
$str2 = "carrrott";
echo levenshtein($str1, $str2); //Outputs 2
?>

Documentation: http://php.net/manual/en/function.levenshtein.php

get_defined_vars()

Here is a handy function when debugging: It returns a multidimensional array containing a list of all defined variables, be them environment, server or user-defined variables, within the scope that get_defined_vars() is called.

Usage:

print_r(get_defined_vars());

Documentation: http://php.net/manual/en/function.get-defined-vars.php

escapeshellcmd()

escapeshellcmd() escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator.

Usage:

<?php
$command = './configure '.$_POST['configure_options'];

$escaped_command = escapeshellcmd($command);
 
system($escaped_command);
?>

Documentation: http://php.net/manual/en/function.escapeshellcmd.php

checkdate()

Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined. Pretty useful to test is a date submitted by an user is valid.

Usage:

<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));

//Output
//bool(true)
//bool(false)
?>

Documentation: http://php.net/checkdate

php_strip_whitespace()

Returns the PHP source code in filename with PHP comments and whitespace removed. This is similar to using php -w from the commandline.

Usage:

<?php
// PHP comment here

/*
 * Another PHP comment
 */

echo        php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
?>

The output:

<?php
 echo php_strip_whitespace(__FILE__); do_nothing(); ?>

Documentation: http://www.php.net/manual/en/function.php-strip-whitespace.php

WordPress snippets to interact with social networks

Display number of Facebook fans in full text on your WordPress blog

If you have a Facebook page for your blog, you might want to display how many fans you have. Simply paste the following code in any of your theme files, where you want your Facebook fan count to be displayed. Don’t forget to add your page ID on line 2!

<?php
	$page_id = "YOUR PAGE-ID";
	$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
	$fans = $xml->page->fan_count;
	echo $fans;
?>

Source: http://wp-snippets.com/display-number-facebook-fans/

Automatically add Twitter and Facebook buttons to your posts

Here is a great snippet to provide Twitter and Facebook buttons to let your visitors share your content with their friends/followers.

Just add the code in your functions.php and save the file.

function share_this($content){
    if(!is_feed() && !is_home()) {
        $content .= '<div class="share-this">
                    <a href="http://twitter.com/share"
class="twitter-share-button"
data-count="horizontal">Tweet</a>
                    <script type="text/javascript"
src="http://platform.twitter.com/widgets.js"></script>
                    <div class="facebook-share-button">
                        <iframe
src="http://www.facebook.com/plugins/like.php?href='.
urlencode(get_permalink($post->ID))
.'&amp;layout=button_count&amp;show_faces=false&amp;width=200&amp;action=like&amp;colorscheme=light&amp;height=21"
scrolling="no" frameborder="0" style="border:none;
overflow:hidden; width:200px; height:21px;"
allowTransparency="true"></iframe>
                    </div>
                </div>';
    }
    return $content;
}
add_action('the_content', 'share_this');

Source: http://www.wprecipes.com/automatically-add-twitter-and-facebook-buttons-to-your-posts

Automatically link Twitter usernames in WordPress

If you’re often quoting Twitter users on your blog, what about automatically link twitter usernames? Here is a nice regular expression to do so. Simply add this code to your functions.php file for it to work.

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');

Source: http://snipplr.com/view/70977/automatically-link-twitter-usernames-in-wordpress/

Show a total share counter (FB, Twitter, G+)

Want to display how many times your post has been shared on Facebook, Twitter and Google+? This is what the snippet below will do for you. Paste it where you want the count to be displayed, within the loop.

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;;
}

Source: http://www.wprecipes.com/wordpress-function-to-show-a-total-share-counter-fb-twitter-g

Automatically add a Google+ button to your posts

I shown you how to add Facebook and Twitter buttons to your posts, but what about Google +? Here’s a snippet that will add a G+ button so your visitors can share them with their circles. Just past the code below in your functions.php and you’re done.

add_filter('the_content', 'wpr_google_plusone');
function wpr_google_plusone($content) {
	$content = $content.'<div class="plusone"><g:plusone size="tall" href="'.get_permalink().'"></g:plusone></div>';
	return $content;
}
add_action ('wp_enqueue_scripts','wpr_google_plusone_script');
function wpr_google_plusone_script() {
	wp_enqueue_script('google-plusone', 'https://apis.google.com/js/plusone.js', array(), null);
}

Source: http://spyrestudios.com/17-time-saving-code-snippets-for-wordpress-developers/

Display your latest Google+ update on your WordPress blog

Are you using Google +, Google social network? If yes, you can easily display your latest G+ update on your WordPress blog using this code snippet.

Copy the code below, and paste it where you want to display your latest Google update. That’s it!

<?php
	include_once(ABSPATH.WPINC.'/rss.php');
	$googleplus = fetch_feed("http://plusfeed.appspot.com/103329092193061943712"); // Replace 103329092193061943712 by your own ID
	echo '<a href="';
	echo $googleplus->items[0]['link']; echo '">';
	echo $googleplus->items[0]['summary'];
	echo '';
?>

Source: http://www.geekeries.fr/snippet/afficher-mise-a-jour-google-plus/

Add a Pinterest “pin it” button for your WordPress blog

The first thing to do is to paste the following snippet where you’d like the “Pin It” button to be displayed. Note that this code must be inserted within the loop.

<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); echo $thumb['0']; ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>

Once done, open your footer.php file and add the pinterest JavaScript code:

<script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>

Source: http://www.marketingtechblog.com/wordpress-pinterest-button/

WordPress tip: How to display recently registered users

Simply paste the code below where you want to display recently registered users. This code will display 5 users, you can change this number on line 2.

<ul class="recently-user">
    <?php $usernames = $wpdb->get_results("SELECT user_nicename, user_url FROM $wpdb->users ORDER BY ID DESC LIMIT 5");
        foreach ($usernames as $username) {
                echo '<li>' .get_avatar($username->comment_author_email, 45).'<a href="'.$username->user_url.'">'.$username->user_nicename."</a></li>";
        }
    ?>
</ul>

Thanks to emoticode for the snippet!!

How to add custom text to WordPress login page

Nothing complicated, paste the code below in your functions.php file. Message can be customized on line 3.

function wps_login_message( $message ) {
    if ( empty($message) ){
        return "<p class='message'>Welcome to this site. Please log in to continue</p>";
    } else {
        return $message;
    }
}
add_filter( 'login_message', 'wps_login_message' );

Thanks to WP Snippy for the tip!

How to clean up wp_head() without a plugin

Paste the following lines of code into your functions.php file:

remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'wp_generator' );
remove_action( 'wp_head', 'start_post_rel_link' );
remove_action( 'wp_head', 'index_rel_link' );
remove_action( 'wp_head', 'adjacent_posts_rel_link' );
remove_action( 'wp_head', 'wp_shortlink_wp_head' );

Thanks to Noumaan Yaqoob for the code!

10 fresh and fantastic jQuery plugins

jqtimeline

Download: http://goto.io/jqtimeline/

Any List Scroller

Download: http://als.musings.it/

Custom Scrollbar

Download: http://manos.malihu.gr/tuts/custom-scrollbar…

Social Count

Download: http://fgte.st/SocialCount/examples/

Facebook wall

Download: http://www.neosmart.de/social-media/facebook-wall/

Supersized!

Download: http://buildinternet.com/project/supersized/

Sidr

Download: http://www.berriart.com/sidr/

Flexisel

Download: http://9bitstudios.github.io/flexisel/

iCheck

Download: http://damirfoy.com/iCheck/

Textillate

Download: http://jschr.github.io/textillate/

How to change contents of a dashboard help tab

Simply paste the code below into your functions.php file.

//hook loading of new page and edit page screens
add_action('load-page-new.php','add_custom_help_page');
add_action('load-page.php','add_custom_help_page');

function add_custom_help_page() {
   //the contextual help filter
   add_filter('contextual_help','custom_page_help');
}

function custom_page_help($help) {
   //keep the existing help copy
   echo $help;
   //add some new copy
   echo "<h5>Custom Features</h5>";
   echo "<p>Content placed above the more divider will appear in column 1. Content placed below the divider will appear in column 2.</p>";
}

Thanks to WP Tuts for the tip!

100 free downloadable PSD mock-ups

What’s in the pack?

The pack contains 100 different actions which can each create a different item such as bags, countless different books, flyers, CDs or Blu-rays cases, magazines, and more. Amongst the hundreds of actions, you’ll even find a mock-up suitable for a bag of chips, or maybe some popcorn.
The mock-ups render up to 12,400 x 9,300 pixels at 300ppi.

How to download

Good news, the mockups are freely downloadable. All you have to do is to go to Webdesigner Depot and enter your email address. The download link will be sent to you by email.

How to use

The mockups comes as Photoshop actions. Using them is super easy: Prepare your artwork, run the action in Photoshop (CS4 or later), and you’re done, here’s a high quality mock-up.

Each mockup action creates a PSD which can be further customized, giving you control of highlights and shadows, as well as letting you apply your branding to the project. Use them for advertising, presentations, webpages, or anything else you can think of, because they’re royalty free.

Click here to download the 100 PSD mockups pack now!

Useful snippets for php developers

Find out if your email has been read

When sending emails, you might want to be able to find out if your email has been read. Here’s a very interesting snippet which log the IP address which read your email, as well as the actual date and time.

<?
error_reporting(0);
Header("Content-Type: image/jpeg");

//Get IP
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
  $ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
  $ip=$_SERVER['REMOTE_ADDR'];
}

//Time
$actual_time = time();
$actual_day = date('Y.m.d', $actual_time);
$actual_day_chart = date('d/m/y', $actual_time);
$actual_hour = date('H:i:s', $actual_time);

//GET Browser
$browser = $_SERVER['HTTP_USER_AGENT'];
    
//LOG
$myFile = "log.txt";
$fh = fopen($myFile, 'a+');
$stringData = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . "\r\n";
fwrite($fh, $stringData);
fclose($fh);

//Generate Image (Es. dimesion is 1x1)
$newimage = ImageCreate(1,1);
$grigio = ImageColorAllocate($newimage,255,255,255);
ImageJPEG($newimage);
ImageDestroy($newimage);
	
?>

Source: http://www.emoticode.net/php/code-to-find-out-if-…

Extract keywords from a webpage

The title said it all: A great code snippet to easily extract meta keywords from any webpage.

$meta = get_meta_tags('http://www.emoticode.net/');
$keywords = $meta['keywords'];
// Split keywords
$keywords = explode(',', $keywords );
// Trim them
$keywords = array_map( 'trim', $keywords );
// Remove empty values
$keywords = array_filter( $keywords );

print_r( $keywords );

Source: http://www.emoticode.net/php/extract-keywords-from-any-webpage.html

Find All Links on a Page

Using the DOM, you can easily grab all links from any webpage. Here’s a working example:

$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
       $href = $hrefs->item($i);
       $url = $href->getAttribute('href');
       echo $url.'<br />';
}

Source: http://snipplr.com/view/70489/find-all-links-on-a-page/

Auto convert URL into clickable hyperlink

In wordpress, if you want to auto convert all URLs in your string into clickable hyperlinks, you can actually do it using the built-in function make_clickable(). If you need to do that outside of wordpress, you can refer to the function’s source code at wp-includes/formatting.php:

function _make_url_clickable_cb($matches) {
	$ret = '';
	$url = $matches[2];
 
	if ( empty($url) )
		return $matches[0];
	// removed trailing [.,;:] from URL
	if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
		$ret = substr($url, -1);
		$url = substr($url, 0, strlen($url)-1);
	}
	return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
}
 
function _make_web_ftp_clickable_cb($matches) {
	$ret = '';
	$dest = $matches[2];
	$dest = 'http://' . $dest;
 
	if ( empty($dest) )
		return $matches[0];
	// removed trailing [,;:] from URL
	if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
		$ret = substr($dest, -1);
		$dest = substr($dest, 0, strlen($dest)-1);
	}
	return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
}
 
function _make_email_clickable_cb($matches) {
	$email = $matches[2] . '@' . $matches[3];
	return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
}
 
function make_clickable($ret) {
	$ret = ' ' . $ret;
	// in testing, using arrays here was found to be faster
	$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
	$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
	$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
 
	// this one is not in an array because we need it to run last, for cleanup of accidental links within links
	$ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
	$ret = trim($ret);
	return $ret;
}

Source: http://zenverse.net/php-function-to-auto-convert-url-into-hyperlink/

Create Data URI’s

Data URI’s can be useful for embedding images into HTML/CSS/JS to save on HTTP requests. The following function will create a Data URI based on $file for easier embedding.

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/

Download & save a remote image on your server

Downloading an image on a remote server and saving it on your own server is useful when building websites, and it’s also very easy to do. The two lines of code below will do it for you.

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

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

Remove Microsoft Word HTML tags

When used, Microsoft Word creates lots of tags: font, span, style, class… These tags are useful inside Word itself, but when you paste a text from Word into a webpage, you’ll end up with lots of useless tags. Here’s a very handy function to remove all Word HTML tags.

function cleanHTML($html) {
/// <summary>
/// Removes all FONT and SPAN tags, and all Class and Style attributes.
/// Designed to get rid of non-standard Microsoft Word HTML tags.
/// </summary>
// start by completely removing all unwanted tags

$html = ereg_replace("<(/)?(font|span|del|ins)[^>]*>","",$html);

// then run another pass over the html (twice), removing unwanted attributes

$html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);
$html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);

return $html
}

Source: http://tim.mackey.ie/CommentView,guid,2ece42de-a334-4fd0-8f94-53c6602d5718.aspx

Detect browser language

If your website is multilingual, it can be useful to detect the browser language to use this language as the default. The code below will return the language used by the client’s 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/

Display number of Facebook fans in full text

If you have a Facebook page for your website or blog, you might want to display how many fans you have. This snippet will help you to get your Facebook fan count, in full text. Don’t forget to add your page ID on line 2.

<?php
	$page_id = "YOUR PAGE-ID";
	$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
	$fans = $xml->page->fan_count;
	echo $fans;
?>

Source: http://www.wprecipes.com/display-number-of-facebook-fans-in-full-text-on-your-wordpress-blog