WordPress code snippets, tricks and cheat sheet

by
on June 8, 2010
(4 minute read)


These are code snippets that I use very frequently while developing advanced or custom WordPress themes. I keep adding and improving this list.

WordPress Post

Custom field

I’ve got invites for a free bank transfer!

Will echo the “thumb” custom field:

$values = get_post_custom_values("thumb"); echo $values[0];

Custom field in a function

Leave ID empty for current post or specify a post ID:

function customfield($name, $id="") {
	$value = get_post_custom_values($name, $id);
	return $value[0];
}

Custom Post loop

The custom loop allows you to include more than one WordPress loop in the same page:

$carrotposts = new WP_Query();
$carrotposts->query('cat=5&s=carrot&paged='.get_query_var('page').'&showposts=10&orderby=date&order=DESC');
if (!$carrotposts->have_posts()) {
  /* no posts */
}else{
  /* we have posts */
  $howmany = $carrotposts->post_count;
  while ($carrotposts->have_posts()) : $carrotposts->the_post();
    /* print posts */
  endwhile;
}
wp_reset_postdata();
unset($carrotposts);

Get first image URL of post

You can send a custom content or leave blank to detect in current post:

function catch_that_image($text = "") {
	if (!$text) {
		global $post, $posts;
		$text = $post->post_content;
	}
	$first_img = '';
	ob_start();
	ob_end_clean();
	$output = preg_match_all('//i', $text, $matches);

	if ($matches[1][0])
		$first_img = $matches [1] [0];

	// no image found display default image instead
	if(empty($first_img)){
		$first_img = "images/default.jpg";
	}
	return $first_img;
}

Or an alternative providing optional post ID:

function catch_that_image($id = '') {
 $first_img = '';
 ob_start();
 ob_end_clean();
 if (!$id) {
 global $post, $posts;
 $id=$post->post_content;
 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
 }else{
 $custompost = get_pages('include='.$id.'');
 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $custompost[0]->post_content, $matches);
 }
 $first_img = $matches[1][0];

 // no image found display default image instead
 if(empty($first_img)){
 $first_img = "/images/default.jpg";
 }
 return $first_img;
}

Resize image with TimThumb

Place TimThumb in your theme folder and name it thumb.php. Send image URL and size.

function timthumb($src, $w, $h) {
	$q = 90;
	$zc = 1;
	$url = get_bloginfo('template_url').'/thumb.php?src='.$src.'&w='.$w.'&h='.$h.'&q='.$q.'&zc='.$zc;
	return $url;
}

Get keywords from the URL

Gets the URL without the domain and converts hyphens and other symbols into spaces. Useful for 404 errors, you could display related tags or do an automatic search into your WordPress.

$keywords = preg_replace("/([^a-zA-Z0-9])/", " ", substr(curPageURL(), strlen(get_bloginfo('url'))+1));

WordPress features

Send an e-mail through WordPress

As simple and effective as that, I use it to send 404 errors and other information to my e-mail as it happens. It is highly customizable and allows you to send HTML emails too.

// sendmail (subject, message)

function sendmail($sub = "Unknown", $text = "(no text)", $to = "[email protected]") {
  $msg = '
    <html>
     <body>
       '.$text.'
     </body>
   </html>';
  $headers = array("From: Garold Walker <[email protected]>", "Content-Type: text/html");
  $h = implode("\r\n",$headers) . "\r\n";
  wp_mail($to, $sub, $msg, $h);
}

Check if user is logged in

if (is_user_logged_in()) { /*yes*/ }else{ /*no*/ }

WordPress paths and bloginfo variables

Website path: bloginfo('url');
Template path: echo bloginfo('template_url');
CSS file path: echo bloginfo('stylesheet_url');

Charset: echo bloginfo('charset');
Blog name: echo bloginfo('name');

Retrieve image gravatar

$hash = md5(strtolower(trim('[email protected]')));
$size = 16; // in pixels
echo 'http://www.gravatar.com/avatar/' . $hash . '?s=' . $size . '';

WordPress hooks

Remove jQuery default loading in WP

Very useful if you want to defer the loading of any Javascript to the bottom of the page. Watch out not to disable it in the admin panel (add it to the header.php of your theme instead of the functions.php):

wp_deregister_script('jquery');

Remove META GENERATOR

function i_want_no_generators() {
  return '';
}
add_filter('the_generator','i_want_no_generators');

Send Emails in HTML format

function wp_set_mail_content_type(){
    return "text/html";
}
add_filter( 'wp_mail_content_type','wp_set_mail_content_type' );

Customize From email address

add_filter('wp_mail_from', 'new_mail_from');
add_filter('wp_mail_from_name', 'new_mail_from_name');

function new_mail_from($old) {
 return '[email protected]';
}

function new_mail_from_name($old) {
 return 'Xavi Esteve';
}

Remove RSD link

remove_action('wp_head', 'rsd_link');

Remove Windows Live Writer

remove_action('wp_head', 'wlwmanifest_link');

PHP

These are PHP codes that don’t use the WordPress ‘framework’ but are helpful to create advanced WordPress themes or to setup the web server.

Cron job

php /home/user_name123/public_html/cron.php

Stupid quotes when exporting database

Sometimes when I export a WordPress database and then import it again, there are some single quotes in the WordPress news rows that pop an error because of incorrect syntax. I usually use Dreamweaver’s regular expressions search to get rid of them:

([a-zA-Z])(')([a-zA-Z])
$1$3

Header info

Choose a status number and the location:

header('HTTP/1.1 200 OK');
header("HTTP/1.1 301 Moved Permanently");
header('HTTP/1.1 307 Temporary Redirect');
header('HTTP/1.1 400 Bad Request');
header('HTTP/1.1 401 Unauthorized');
header('HTTP/1.1 403 Forbidden');
header('HTTP/1.1 404 Not Found');
header('HTTP/1.1 420 Enhance Your Calm');
header('HTTP/1.1 500 Internal Server Error');
header('HTTP/1.1 503 Service Unavailable');
header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
header("Location: https://xaviesteve.com//");
die();

Set default time zone

date_default_timezone_set('Europe/Madrid');
date_default_timezone_set('Europe/London');

Trim text without cutting the words and adding hellip when necessary

/* This function will trim text without
cutting it in the middle of the word and
adding … if longer
*/
function trimtext($text, $length) {
	$words = explode(" ", $text);
	$newtext = "";
	$addhellip = "";
	foreach ($words as $word) {
		if (strlen($newtext." ".$word) < $length) {
			$newtext .= " ".$word;
		}else{
			$addhellip = 1;
			break;
		}
	}
	if ($addhellip) {$newtext .= "…";}
	return $newtext;
}

WordPress Relative date (without/no plugin needed)

WordPress has a function for that:

<?php relative_post_the_date(); ?>

Or also:

Published <?=human_time_diff(get_the_time('U'), current_time('timestamp'))?> ago.

Things I’m buying on Amazon this week

And here’s a function to convert seconds to relative date. Useful to display user-friendly times. Can be highly customized: “3 minutes ago”, “in 2 hours”, “for the last 6 months”, “takes 10 seconds”…

function relativedate($secs) {
  $second = 1;$minute = 60;$hour = 60*60;$day = 60*60*24;$week = 60*60*24*7;$month = 60*60*24*7*30;$year = 60*60*24*7*30*365;
  if ($secs <= 0) { $output = "now";
  }elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
  }elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
  }elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
  }elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
  }elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
  }elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
  }elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
  }else{ $output = " more than a decade ago"; }
  if ($output <> "now"){$output = (substr($output,0,2)<>"1 ") ? $output."s" : $output;}
  return $output;
}
echo relativedate(60); // 1 minute

Shorten a URL with Bit.ly’s simple API

function getBitLy($url) {
	$login = "yourusername";
	$appkey = "yourbitlyapi";
	$format = "txt";
	return file_get_contents('http://api.bit.ly/v3/shorten?login='.$login.'&apiKey='.$appkey.'&uri='.urlencode($url).'&format='.$format);
}

Plugin Development

Add a style sheet to your plugin Admin panel

# stylesheet
function admin_register_head() {
    $siteurl = get_option('siteurl');
    $url = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/style.css';
    echo "
\n";
}
add_action('admin_head', 'admin_register_head');

Add a button in your Admin panel sidebar at the top above Dashboard

add_action('admin_menu', '_add_menu_in_panel');

function _add_menu_in_panel() {
	if (function_exists('current_user_can')) {
		if (!current_user_can('manage_options')) return;
	}else{
		global $user_level;
		get_currentuserinfo();
		if ($user_level < 8) return;
	}
	if (function_exists('add_options_page')) {
		add_menu_page( 'textintitletag', 'textinbutton', 'edit_pages', 'pluginname', 'functiontoloadwhenopened', get_bloginfo('url').'/favicon.png', '-1' );
	}
}

Top photo by darwinbell

Looking for cool gift ideas? TrendLiker.com lists hundreds of nice items and lets you know when they go on sale on Amazon.

Did you enjoy this article?

Grab me a coffee ☕

2 comments

  • jehzlau says:

    ohhh.. so that’s what they call it.. Relative Date.. :D I was searching about how to do it… the published ____ seconds ago, minutes ago, etc. :D

    Thanks for the code snippets :D

Follow me for cool new products and interesting findings on graphic design, web development, marketing, startups, life and humor.


/*Twitter*/ !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); /*Facebook (function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) {return;}js = d.createElement(s); js.id = id;js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=28624667607";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));*/ /*Google+*/ window.___gcfg = {lang: 'en-GB'};(function() {var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;po.src = 'https://apis.google.com/js/plusone.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);})();
Airbnb 25€ discount