Huge Collection of Code Snippets: HTAccess, PHP, WordPress, jQuery, HTML, CSS

.htaccess made easy

Please excuse this self-serving, miscellaneous post, but I’ve just got to purge all of these code snippets and scraps collected over the years. Whenever I update this site, I place any removed/unused code snippets into a giant note file for future reference, just in case. There’s all sorts of different types of code and snippets that just keep growing and growing and.. and finally it gets to a point where I just need to dump everything and start fresh. That is the purpose of this post.

SO rather than delete some of these gems, I thought it would be useful to post them here at Perishable Press and share with anyone who finds them useful. But be warned, these code snippets and scraps are provided wholesale, with little or no explanation, and should be used only if you truly know what you are doing. And so with that said, here is approximately five years’ worth of miscellaneous snippets, scripts, and hacks. Enjoy!

.htaccess

I do a lot of experimenting with htaccess, revising existing rules, updating blacklists, trying new techniques, and so forth. The result of all this fiddling is basically a ton of htaccess code scraps that work great, but for whatever reason are no longer needed, have been replaced, or whatever.

These snippets function independently, with each block of code functioning independently of the others. I definitely do not recommend copy/pasting blocks of code en masse, rather each should be applied and tested thoroughly before adding more snippets. That said, these htaccess code snippets are organized into several sections: performance, canonicalization, security, and miscellaneous.

Performance snippets

# DISABLE ETAGS
<filesMatch "\\.(ico|pdf|flv|jpe?g?|png|gif|js|css|swf|txt|mp3|avi|mpe?g?|wmv)$">
 FileETag none
</filesMatch>

# FILE COMPRESSION
<ifModule mod_deflate.c>
 AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/x-javascript
 BrowserMatch ^Mozilla/4 gzip-only-text/html
 BrowserMatch ^Mozilla/4\.0[678] no-gzip
 BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</ifModule>

Canonical snippets

# CANONICAL ROBOTS.TXT
<ifModule mod_alias.c>
 RedirectMatch 301 ^/(.*)/robots\.txt http://example.com/robots.txt
</ifModule>

# CANONICAL SITEMAP
<ifModule mod_alias.c>
 RedirectMatch 301 /sitemap\.xml$ http://example.com/sitemap-press.xml
 RedirectMatch 301 /sitemap\.xml\.gz$ http://example.com/sitemap-press.xml.gz
</ifModule>

# MULTIPLE SITEMAPS
<ifModule mod_rewrite.c>
 RewriteBase /
 RewriteCond %{REQUEST_URI} !^/sitemap\-(perish|press)\.xml(.gz)?$ [NC]
 RewriteRule /sitemap\-(.*)?\.?(.*)?(.*)? http://example.com/sitemap-$1.$2$3 [R=301,L]
</ifModule>

# CANONICAL XMLRPC
<ifModule mod_alias.c>
 RedirectMatch 301 /press/(.*)/xmlrpc\.php$ http://example.com/press/xmlrpc.php
</ifModule>

# FORCE TRAILING SLASH
<ifModule mod_rewrite.c>
 RewriteCond %{REQUEST_URI} /+[^\.]+$
 RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</ifModule>

# ROOT CANONICALIZATION
<ifModule mod_rewrite.c>
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php [NC]
 RewriteRule ^index\.php$ http://example.com/ [R=301,L]
 RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
 RewriteRule (.*) http://example.com/$1 [R=301,L]
</ifModule>

# CANONICALIZATION
<ifModule mod_alias.c>
 # REMOVE INTITIAL INDEX.PHP
 RedirectMatch 301 index.php/(.*) http://example.com/press/$1
</ifModule>
<ifModule mod_rewrite.c>
 # REMOVE ADDITIONAL INDEX.PHP
 RewriteBase /press/
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.(html|php)\ HTTP/
 RewriteRule ^(([^/]+/)*)index\.(html|php)$ http://example.com/press/$1 [R=301,L]
 # FORCE TRAILING SLASH
 RewriteCond %{REQUEST_URI} /+[^\.]+$
 RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
</ifModule>

# REDIRECT PAGE QUERIES
<ifModule mod_rewrite.c>
 RewriteCond %{REQUEST_URI} !example.com [NC]
 RewriteCond %{REQUEST_URI} !^/$ [NC]
 RewriteCond %{QUERY_STRING} ^p\= [NC]
 RewriteRule (.*) http://example.com/? [R=301,L]
</ifModule>

 # REDIRECT SUBDIRECTORIES
<ifModule mod_rewrite.c>
 RewriteBase /
 RewriteCond %{REQUEST_URI} ^/(perish|press)/?$
 RewriteRule .* http://example.com/ [R=301,L]
</ifModule>

# CLEAN EXTERNAL LINKS
<ifModule mod_rewrite.c>
 RewriteBase /
 RewriteCond %{QUERY_STRING} scamdex [NC]
 RewriteRule .* http://example.com/$1? [R=301,L]
</ifModule>

Security snippets

# HOTLINK PROTECTION
<ifModule mod_rewrite.c>
 RewriteCond %{HTTP_REFERER} !^$
 RewriteCond %{REQUEST_FILENAME} -f
 RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g?|png)$ [NC]
 RewriteCond %{REQUEST_FILENAME} !/hotlink\-(01|02).gif$ [NC]
 RewriteCond %{HTTP_REFERER} !^https?://([^.]+\.)?example\. [NC]
 # RewriteRule \.(gif|jpe?g?|png)$ - [F,NC,L]
 RewriteRule \.(gif|jpe?g?|png)$ http://example.com/wordpress/hotlink-02.gif [R,NC,L]
</ifModule>

# BLOCK EVIL REQUESTS
<ifModule mod_rewrite.c>
 Options +FollowSymLinks
 RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
 RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
 RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
 RewriteRule .* blacklist.php [F,L]
</ifModule>

# BLOCK SCUM REFERRERS
<ifModule mod_rewrite.c>
 RewriteCond %{HTTP_REFERER} (.*)secondchanceranch(.*) [NC]
 RewriteRule .* - [F,L]
</ifModule>

# DENY ACCESS TO NO-REFERRER REQUESTS
<ifModule mod_rewrite.c>
 RewriteCond %{REQUEST_METHOD} POST
 RewriteCond %{REQUEST_URI} .wp-comments-post\.
 RewriteCond %{HTTP_REFERER} !.*example\. [OR,NC]
 RewriteCond %{HTTP_USER_AGENT} ^$
 RewriteRule .* - [F,L]
</ifModule>

# REDIRECT URL (fafich.ufmg.br)
<ifModule mod_rewrite.c>
 RewriteCond %{REQUEST_FILENAME} .*
 RewriteCond %{HTTP_REFERER} ^https?://([^.]+\.)?ufmg\. [NC]
 RewriteRule .* - [F,L]
</ifModule>

Miscellaneous snippets

# SUBSCRIPTION PLUGIN
<ifModule mod_rewrite.c>
 RewriteBase /
 RewriteCond %{QUERY_STRING} !wp\-subscription\-manager [NC]
 RewriteCond %{REQUEST_URI}  ^/press/$ [NC]
 RewriteRule .* http://example.com/ [R=301,L]
</ifModule>

PHP snippets

Next up, we’ve got some PHP snippets that do everything from importing and displaying Twitter tweets, filtering globals, and creating MySQL database tables.

Display FeedBurner subscriber count

This snippet conditionally displays your FeedBurner subscriber count: if the data is available (rare these days), the number of subscribers will be displayed; if the data isn’t available – or if the plugin function doesn’t exist – an alternate message is displayed. Requires a plugin to display FeedBurner count in plain text (you can use any plugin, just change the code).

<div class="subcount">
	<small>
		<?php if(function_exists('fc_feedcount')) { ob_start(); fc_feedcount(); $count = ob_get_contents(); ob_end_clean();
			 if($count == 'N/A' || $count == '0') { echo '6500 Feed Subscribers'; } else { echo $count . ' Feed Subscribers'; } } else { echo '6500 Feed Subscribers'; } ?>
	</small>
</div>

Import & display latest Twitter tweet

Nice little PHP snippet for displaying your latest tweet. A few lines are commented out, so feel free to go thru and customize things as desired. The only required edits are for the first two variables, $username & $feed. Everything else should be plug-n-play, ready to paste into your sidebar or anywhere else on the page (outside of the loop if using WordPress or similar).

<?php // import & display latest tweet
$username = "perishable";
$feed = "http://search.twitter.com/search.atom?q=from:".$username."&rpp=2";
// $prefix = '<h3>Perishable Press</h3>';
// $suffix = '<p><a href="http://twitter.com/'.$username.'">Follow me on Twitter</a>';
function parse_feed($feed) {
    $stepOne = explode('<content type="html">', $feed);
    $stepTwo = explode('</content>', $stepOne[1]);
    $tweet = $stepTwo[0];
    $tweet = str_replace("&lt;", "<", $tweet);
    $tweet = str_replace("&gt;", ">", $tweet);
    return $tweet;
}
$latest_tweet = file_get_contents($feed);
// echo stripslashes($prefix) . parse_feed($latest_tweet) . stripslashes($suffix);
echo parse_feed($latest_tweet);
?>

Capture the requested URI

This snippet is more powerful than you realize :)

$requestURI = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']';

Clean up global variables

This snippet is more of an example of how to convert strings to lowercase characters, and then clean them up for use in scripts, etc.

$_POST["name"] = strtolower(stripslashes(trim(htmlspecialchars($_POST["name"]))));
$_POST["message"] = strtolower(stripslashes(trim(htmlspecialchars($_POST["message"]))));

Create database tables with PHP

This code was used for a custom version of my Ajax-powered error log. When I used it, this SQL query was executed directly in phpMyAdmin, so it should also work when executed from a normal PHP file.

CREATE TABLE  `errorlog` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `logtime` varchar(200) NOT NULL default '',
  `request` varchar(200) NOT NULL default '',
  `referer` varchar(200) NOT NULL default '',
  `qstring` varchar(200) NOT NULL default '',
  `address` varchar(200) NOT NULL default '',
  `country` varchar(200) NOT NULL default '',
  `theme` varchar(200) NOT NULL default '',
  `agent` varchar(200) NOT NULL default '',
  `error` varchar(200) NOT NULL default '',
  `image` BLOB NOT NULL default '',
  PRIMARY KEY  (`id`),
  cur_timestamp TIMESTAMP(8)
) AUTO_INCREMENT = 1

IP lookup from database

Simple script that does an IP lookup from a database (such as the one from previous example), and then echoes the country, city, and address information to the browser. Basically we’re making the query result more flexible for design purposes.

// ip lookup from database
$ip = $row["address"];
$url = "http://api.hostip.info/get_html.php?ip=".$ip;
$contents = file_get_contents($url);
$values = split("[\n|\r]",$contents);

	$count = count($values);
	for($i = 0; $i < $count; $i++) {
		if($i != $count-1) {
			echo $values[$i] . "\n";
		}
	}

This will echo something like the following to the browser:

Country: UNITED STATES (US)
City: Seattle, WA
IP: 123.456.789

Display source code of web pages

This is from the PHP manual, using the file function to display the source code of any URL. This is fun to play around with, and the basic file functionality I’ve used on a number of projects. Phun stuph! :)

<?php // display source code
$lines = file('http://google.com/'); // pick teh url
foreach ($lines as $line_num => $line) {
	// loop thru each line and prepend line numbers
	echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

WordPress snippets

Ah yes, the WordPress snippets.. Lots of random gems here, but probably nothing that’s gonna rock your world. It’s mostly just experimental and/or custom code that is no longer used on the site. As with other snippets in this massive code dump, remember to backup your stuff before experimenting and uploading to your server.

My favorite template tags

Just kidding. But it’s nice to have them ready to use in new themes. I tend to implement WordPress tags the same way across sites, so I put them all together into nice pile for easy pickinz.

<?php wp_list_pages('exclude=6&title_li=<h2>Pages</h2>'); ?>
<?php wp_list_pages('exclude=48,376,610,613,614,725&title_li=<h2>Pages</h2>'); ?>
<?php wp_list_categories('show_count=0&order=desc&title_li=<h2>Categories</h2>'); ?>
<?php wp_link_pages(array('before'=>'Pages: ', 'next_or_number'=>'number')); ?>
<?php wp_list_bookmarks(); // $post->post_title ?>
<?php wp_list_pages('title_li=&exclude=6'); ?>
<?php wp_get_archives('type=monthly'); ?>

(Try to) force WP FTP

Is this forcing? I don’t know, but that’s what it feels like sometimes trying to wrestle with WP FTP on differently configured systems. This snippet usually helps with WordPress’ admin-FTP functionality. Like when you’re trying to update your plugins for example. When auto-update fails, try placing this code into your site’s wp-config.php file, just above where it says, “That’s all, stop editing!”. Edit the different variables according to your specific setup.

// encourage WP FTP
define('FS_CHMOD_FILE', 0755);
define('FS_CHMOD_DIR', 0755);
define('FS_METHOD', 'ftpext');
define('FTP_BASE', '/httpdocs/');
define('FTP_CONTENT_DIR', '/httpdocs/wp-content/');
define('FTP_PLUGIN_DIR ', '/httpdocs/wp-content/plugins/');
define('FTP_USER', 'username');
define('FTP_PASS', 'password');
define('FTP_HOST', '123.456.789.000:21');
define('FTP_SSL', false);

Display latest comments for each post

Normally, WordPress displays comments on single post views via the comments.php theme template file. But you can also display comments for each post on the home page and other non-single page views (archive, category, search, etc.). For more information, see this WP forum thread.

<?php // display latest comments for each post on non-single page views
$comment_array = array_reverse(get_approved_comments($wp_query->post->ID));
$count = 1; // number of comments
if ($comment_array) { ?>

	<h3><?php comments_number('No comment', '1 comment', '% comments'); ?></h3>
	<ul>
	<?php foreach ($comment_array as $comment) {
		if ($count++ <= 2) { ?>
		<li><?php comment_author_link(); ?>: <?php comment_excerpt(); ?></li>
		<?php }
	} ?>
	</ul>

<?php } else {
	echo '<p>No comments yet.</p>';
} ?>

Display conditional comment links

This snippet conditionally displays WordPress’ comments_number() tag, depending on whether or not comments are open for the post. So for example, in my Requiem theme, when browsing the archives, categories, and so on, each post displays “Post a comment” if comments are open with no comments, or else “Comments” if comments are closed with no comments. If there are comments, the number is displayed. This is an example of “obsessive design” :)

<div class="metadata">
	By <?php the_author(); ?> on <?php the_time("l, F j, Y"); ?><br />
	<a href="#comments">
		<?php // conditional comment link text
		if (comments_open()) :
			comments_number(__('Post a Comment'), __('1 Response'), __('% Responses'));
		else :
			comments_number(__('Comments'), __('1 Response'), __('% Responses'));
		endif; ?>
	</a>
</div>

Multiple themes outside of WordPress

With newer versions of WordPress, this sort of stuff is no longer required, but it does enable advanced customization of your WordPress web pages, especially the home page when using multiple themes for your site. I continue to add new themes to the site, and along the way this code provided the flexibility required for custom themes on web pages outside of WordPress.

<?php require_once("./press/wp-blog-header.php");
if ( !empty($_COOKIE["wptheme" . COOKIEHASH]) ) {
	$press_theme = $_COOKIE["wptheme" . COOKIEHASH];
} elseif ( empty($_COOKIE["wptheme" . COOKIEHASH]) ) {
	$press_theme = get_current_theme();
}
if     ( $press_theme == "Apathy" ) :         include_once("./press/wp-content/themes/apathy/index.php");
elseif ( $press_theme == "Bananaz" ) :        include_once("./press/wp-content/themes/bananaz/index.php");
elseif ( $press_theme == "Casket" ) :         include_once("./press/wp-content/themes/casket/index.php");
elseif ( $press_theme == "DOS_FX" ) :         include_once("./press/wp-content/themes/dosfx/index.php");
elseif ( $press_theme == "Entropy" ) :        include_once("./press/wp-content/themes/entropy/index.php");
elseif ( $press_theme == "Finished" ) :       include_once("./press/wp-content/themes/finished/index.php");
elseif ( $press_theme == "Garbage" ) :        include_once("./press/wp-content/themes/garbage/index.php");
elseif ( $press_theme == "Headline" ) :       include_once("./press/wp-content/themes/headline/index.php");
elseif ( $press_theme == "Information" ) :    include_once("./press/wp-content/themes/information/index.php");
elseif ( $press_theme == "Jupiter" ) :        include_once("./press/wp-content/themes/jupiter/index.php");
elseif ( $press_theme == "Killer" ) :         include_once("./press/wp-content/themes/killer/index.php");
elseif ( $press_theme == "Lithium" ) :        include_once("./press/wp-content/themes/lithium/index.php");
elseif ( $press_theme == "minimalist" ) :     include_once("./press/wp-content/themes/minimalist/index.php");
elseif ( $press_theme == "Naked" ) :          include_once("./press/wp-content/themes/naked/index.php");
elseif ( $press_theme == "Optimized" ) :      include_once("./press/wp-content/themes/optimized/index.php");
elseif ( $press_theme == "Perishable" ) :     include_once("./press/wp-content/themes/perishable/index.php");
elseif ( $press_theme == "Quintessential" ) : include_once("./press/wp-content/themes/quintessential/index.php");
elseif ( $press_theme == "Requiem" ) :        include_once("./press/wp-content/themes/requiem/index.php");
elseif ( $press_theme == "Serious" ) :        include_once("./press/wp-content/themes/serious/index.php");
else :                                        include_once("./press/wp-content/themes/default/index.php");
endif;
?>

Multiple themes outside of WordPress (alt version)

Pretty much the same thing happening as with the previous example, with additional logic thrown in to serve a second WordPress installation depending on IP address. This code was used during the development of the new Perishable Press site.

<?php // custom root index.php
if ($_SERVER['REMOTE_ADDR'] == '123.456.789.000' || $_SERVER['REMOTE_ADDR'] == '000.987.654.321') {
	define('WP_USE_THEMES', true);
	require_once("./perish/wp-blog-header.php");
} else {
	require_once("./press/wp-blog-header.php");
	if (!empty($_COOKIE["wptheme".COOKIEHASH])) {
		$press_theme = $_COOKIE["wptheme".COOKIEHASH];
	} elseif (empty($_COOKIE["wptheme".COOKIEHASH])) {
		$press_theme = get_current_theme();
	}
	if     ( $press_theme == "Apathy" ) :  include_once("./press/wp-content/themes/apathy/index.php");
	elseif ( $press_theme == "Bananaz" ) : include_once("./press/wp-content/themes/bananaz/index.php");
	// ... ( $other_themes ) ...
	elseif ( $press_theme == "Serious" ) : include_once("./press/wp-content/themes/serious/index.php");
	else :                                 include_once("./press/wp-content/themes/default/index.php");
	endif;
} ?>

Display popular posts from external WP database

This was an attempt to display popular posts from another WordPress site. It’s based on tutorial, which works great when pulling results from the same database, but trying to get it to work with an external WP database was a no-go. Hopefully someone knows what’s up – it would be extremely useful ;)

<?php // pop posts from external WP database
function listPopularPosts() {
	global $wpdb;
	$strBuidler = '';
	$press_db = new wpdb('database', 'password', 'username', 'localhost');
	$result = $press_db->get_results("SELECT comment_count, ID, post_title FROM wp_posts ORDER BY comment_count DESC LIMIT 0 , 5");
	foreach ($result as $post) {
		setup_postdata($post);
		$postId = $post->ID;
		$title = $post->post_title;
		$commentCount = $post->comment_count;
		if ($commentCount != 0) {
			$strBuidler .= '<li>';
			$strBuidler .= '<a href="' . get_permalink($postId) . '" title="' . $title . '">' . $title . '</a> ';
			//$strBuidler .= '(' . $commentCount . ')';
			$strBuidler .= '</li>';
		}
	}
	return $strBuidler;
} ?>
<!-- put this next part into your theme template file -->
<h2>Popular Posts</h2>
<ul>
	<?php echo(listPopularPosts()); ?>
</ul>

If you can get it to work, let me know. Otherwise, here’s another attempt at making it happen:

<h2>Popular Posts</h2>
<ul>
	<?php $press_db = new wpdb('database', 'password', 'username', 'localhost');
		 $popular_posts = $press_db->get_results("SELECT id, post_title, post_name FROM wp_posts ORDER BY comment_count DESC LIMIT 0, 3");
		foreach($popular_posts as $post) {
			$postid = $post->id;
			echo '<li>http://example.com/press/' . get_permalink($postid) . '/</li>' . "\n";
		} ?>
</ul>

Quick copy/paste shortcode snippet

Pop this snippet into your theme’s single.php somewhere in the loop and watch the sparks fly. Not really. It just displays a field with the post’s shortlink, so visitors can quickly grab the URL and share at their favorite social media sites. Shortlink URL gets highlighted when the user clicks anywhere within the input field.

<?php if (function_exists('get_shortlink')) { // WP 3+ ?>
<div class="short-url">Short <abbr title="Uniform Resource Locator">URL</abbr>: <input onClick="this.focus(); this.select();" value="<?php echo get_shortlink(get_the_ID()); ?>" size="30" type="text" /></div>
<?php } ?>

And for us connoisseurs running older versions of WordPress, use this snippet instead:

<div class="short-url">Short <acronym title="Uniform Resource Locator">URL</acronym>: <input onFocus="this.select();" value="<?php shortenURL(get_permalink()); ?>" size="30" type="text" /></div>

Exclude category from feeds

Self-explanatory. Add this to your functions.php file and set the WP query using any of the available parameters. Great for excluding categories or customizing feeds in all sorts of fun ways.

// custom feed query
function customFeedquery($query) {
	if(is_feed()) {
		$query->set('cat','-8'); // exclude category 8
		return $query;
	}
}
add_filter('pre_get_posts', 'customFeedquery');

JavaScript/jQuery snippets

Here are some interesting and useful JavaScript & jQuery snippets collected over the years during rounds of experimentation, testing, and developing. Again, nothing jaw-droppingly astounding, but perhaps a few new tricks to help improve your website.

Open external links in new tab

Kicking it off with a quick snippet to open links with rel="external" in a new tab or browser window. This is a great way to apply some unobtrusive behavior with a single line of jQuery.

$('a[rel^="external"],a[rel$="external"]').attr({target:"_blank",title:"Opens in a new tab or window"}).append('');

Select all paragraphs that contain images

Probably don’t need to include this, but it reminds me of stuff, so here it is.

$("p:has(img)");

Ajax load & update content

Say you want to load some data dynamically using Ajax, and then have it update every five seconds. Easy: HTML5, Add jQuery and mix:

<html>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
	$(document).ready(function() {
		$("#ajax-content").load("process.php");
		var refreshId = setInterval(function() {
			$("#ajax-content").load("process.php");
		}, 5000); // 5 seconds
	});
</script>
<div id="ajax-content"></div>
</html>

Of course, process.php has to do something, like process data, pull from a database, whatever. When new data is available, it will be displayed in the #ajax-content box, updated at an interval of 5 seconds (5000 milliseconds). I use this technique all over the place – es muy excellente.

Auto-focus search field

I use this snippet on my all-dark “Perishable” theme to auto-focus the search input field when the user clicks a “search” link. The search link is at the top of the page, and when the user clicks it, the page is scrolled to the search form, which is displayed in the footer area. So with this code in place, the search field is auto-highlighted after the scroll. Note that #s is the id of the input field.

<script>
	$(document).ready(function(){
		$("#search-link").bind('click',function(){
			setTimeout(function(){$('#s').focus();},25);
			return true;
		});
	});
</script>

Make first word bold

Snagged from here, this gem matches the first word in all target elements. So you can wrap additional markup around the first word, or tweak it to do just about anything.

<script>
$('#links a').each(function(){
	var me = $(this);
	me.html( me.text().replace(/(^\w+)/,'<strong>$1</strong>') );
});
</script>

Or here is another way of doing it:

<script>
$('#links a').each(function(){
	var me = $(this), t = me.text().split(' ');
	me.html( '<strong>'+t.shift()+'</strong> '+t.join(' ') );
});
</script>

Expanding code box (customized)

This is a customized version of Chris Coyier’s expanding code box posted at DigWP.com some time ago. This code was used in the current theme, and is included here as reference.

$(function(){
	$('article.category-code pre').hover(function(){
		var codeInnerWidth = $('code',this).width() + 15;
		if(codeInnerWidth > 475){
			$(this).stop(true,false).css({'overflow-x':'scroll'}).animate({width:860},{'duration':'fast','easing':'swing'});
			$('#sidebar').css({'opacity':'0.5'});
		}else if(codeInnerWidth > 860){
			$(this).stop(true,false).css({'overflow':'auto'}).animate({width:860},{'duration':'fast','easing':'swing'});
			$('#sidebar').css({'opacity':'0.5'});
		}
	},function(){
		$(this).stop(true,false).css({'overflow':'hidden'}).animate({width:475},{'duration':'fast','easing':'swing'});
		$('#sidebar').css({'opacity':'1.0'});
	});
});

Another expanding code box script I was playing around with, but never ended up using anywhere:

$('pre').hover(function(){
		$(this).stop().animate({width:890},300).css({'overflow-x':'scroll'});
		$('#sidebar').css({'opacity':'0.5'});
	},function(){
		$(this).stop().animate({width:550},300).css({'overflow-x':'scroll'});
	$('#sidebar').css({'opacity':'1.0'});
});
$('pre').hover(function(){
	var codeInnerWidth = $('code',this).width() + 10;
	if(codeInnerWidth > 555){
		$(this).stop().animate({width:890},300).css({'overflow-x':'scroll'});
		$('#sidebar').css({'opacity':'0.5'});
	}
},function(){
	$(this).stop().animate({width:555},300).css({'overflow-x':'auto'});
		$('#sidebar').css({'opacity':'1.0'});
	});
});

HTML snippets

Here are several HTML nuggets that I use in various themes here at the site. I suppose they could be useful in other scenarios as well, but it doesn’t really matter now, does it?

Custom subscribe to comments markup

I’ve got to admit, back in the day I used to hack the heck out of my WordPress core files and plugins. For example, the Subscribe to Comments plugin used in my older /press/ installation of WordPress, I hacked the markup used for the comment-subscription form. And I did it so poorly. That’s the real sad part. Here is what the current plugin form markup looks like:

<!-- /perish/ -->
<p style="clear: both;" class="subscribe-to-comments">
	<input name="subscribe" id="subscribe" value="subscribe" style="width: auto;" type="checkbox">
	<label for="subscribe">Notify me of followup comments via e-mail</label>
</p>

..and here’s what it looks like in my WP 2.3.3 install:

<!-- /press/ -->
<div style="clear: both;" class="subscribe-to-comments">
	<p>
		<strong id="strong">Subscribe to comments</strong><br />
		<span id="subscribe-via-email">
			<input name="subscribe" id="subscribe" value="subscribe" style="width: auto;" checked="checked" type="checkbox">
			<label id="label" for="subscribe">Notify me of follow-up comments via email</label>
		</span><br />
		<span id="subscribe-to-feed"><small id="small">[or]</small>
		<a href="" title="">Subscribe to comments on this post via <acronym title="Really Simple Syndication">RSS</acronym></a></span>
	</p>
</div>

Seriously, that was like 5 years ago ;)

Copy/paste XHTML 1.0 (Strict) template

Before it went HTML5, WordPress was XHTML 1.0. So of course I had a quick copy/paste template ready to go for any occasion. Includes <script> & <style>!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<title>XHTML 1.0 Strict</title>
		<script type="text/javascript">
			<!--//--><![CDATA[//><!--
			//--><!]]>
		</script>
		<style type="text/css">
			<!--/*--><![CDATA[/*><!--*/
			/*]]>*/-->
		</style>
	</head>
	<body>
	</body>
</html>

CSS snippets

The CSS snippets are fun to me. I like to share them, but don’t always have the time. Oh well, now is the perfect excuse!

Cool font stacks

Some of the various font stacks that have caught my eye over the years.

font-family: Oxford, Garamond, serif;
font-family: Torque, Tahoma, sans-serif;
font-family: Consolas, Monaco, Courier, monospace;
font-family: 'BPReplay Regular', Arial, sans-serif
font-family: Palatino, Georgia, Helvetica, sans-serif;
font-family: Consolas, Menlo, 'DejaVu Sans Mono', monospace;
font-family: Miso, 'Lucida Sans Unicode', 'Lucida Grande', sans-serif;
font-family: 'myriad-pro-1', 'myriad-pro-2', HelveticaNeue, Helvetica, Arial, serif;
font-family: Monaco, 'Courier New', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
font-family: 'Verlag Condensed', 'Abadi MT Condensed', 'Futura Std Light Condensed', 'Futura Condensed', 'Gill Sans', 'Arial Narrow', Calibri, 'Trebuchet MS', Georgia, sans-serif;
font-family: 'calluna-1', 'calluna-2', 'Georgia', 'Nimbus Sans L', serif;
font-family: 'adelle-1', 'adelle-2', Georgia, serif;
font-family: 'ronnia-1', 'ronnia-2', sans-serif;

Force vertical scrollbars

This works for me in every browser I’ve tried.

html, body {
	height: 100%;
	margin: 0 0 1px;
	padding: 0;
	}

Some great-looking heading typography

Especially on Firefox/Mozilla browsers, these CSS styles make for some awesome h2 heading tags.

firefox h2.tuf {
	 -x-system-font: none;
	font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif;
	font-size: 24px;
	font-size-adjust: none;
	font-stretch: normal;
	font-style: italic;
	font-variant: normal;
	font-weight: normal;
	line-height: 35px;
	margin: 0;
	padding: 14px 15px 3px 0;
	text-shadow: 0 1px 0 #FFFFFF;
	}

pre styles for older Internet Explorer

These CSS styles target IE6 and IE7, respectively. When applied, scrollbars for <pre> tags will function decently in IE6/7.

/* IE6 and IE7 */
* html pre {
	padding-bottom: 25px;
	overflow-y: hidden;
	overflow: visible;
	overflow-x: auto;
	}
*:first-child+html pre {
	padding-bottom: 25px;
	overflow-y: hidden;
	overflow: visible;
	overflow-x: auto;
	}

CSS3 text effects

A variety of snazzy CSS typography effects..

.clean-black-text-on-white {
	color: #222; text-shadow: 0 2px 1px #bbbaba;
	filter: dropshadow(color=#bbbaba, offX=0,offY=1);
	}
.soft-grey-shadow-on-grey {
	background-color: #474747;
	color: #999; text-shadow: 0 3px 8px #2a2a2a;
	filter:dropshadow(color=#bbbaba, offX=0,offY=1);
	}
.light-glow-on-dark-text-w-grey-bg {
	color: #222; text-shadow: 0px 2px 3px #555;
	}
.pure-css-letterpress-effect {
	color: #222; text-shadow: 0px 2px 3px #555;
	}

Centered horizontal list

Many ways to do this, but this one works great for most of my layouts. To really see what it’s doing, add a temporary border to each selector and refresh the browser.

nav ul {
	list-style: none;
	margin: 0 auto;
	width: 800px;
	padding: 0;
	}
nav li {
	float: left;
	}

Display URL after each hyperlink

This is an old CSS trick to display the URL from the href attribute after each link. This is a commonly used technique in print stylesheets.

a:after {
	content: attr(href);
	}

When applied, links will be displayed something like this:

Google Homepage http://google.com/

Other stuff

Lastly, some miscellaneous stuff, well.. mostly robots.txt rules that you either already know, or won’t ever need because it only applies to this site. Posted here for future reference.

Disallow the ia_archiver

For some sites, the ia_archiver bot is like butter, you don’t even know it’s been there. For other sites, however, it can’t seem to get it right. If you decide to stop the madness, these simple robots.txt rules will do the job.

User-agent: ia_archiver
Disallow: /

Testing robots.txt

Last and certainly least, here is a set of rules that I use to check my robots.txt file using Google’s Webmaster’s Tools tester thing (gotta log in to your Google account to use it). Totally not useful to anyone, I realize, but they continue to serve me well :)

Update 2012 05 02: Changed perishablepress.com to example.com because googlebot et al keep crawling these URLs as if they were actual hyperlinks. Which they’re not.

# @ https://www.google.com/webmasters/tools/robots

http://example.com/press/wp-login.php?action=lostpassword
http://example.com/press/2012/05/01/livecalendar-test/
http://example.com/press/wp-comments-post.php
http://example.com/press/wp-admin/edit.php
http://example.com/press/wp-admin/post.php
http://example.com/press/index.php?tag=mac
http://example.com/press/wp-register.php
http://example.com/press/comments/feed/
http://example.com/press/wp-login.php
http://example.com/press/xmlrpc.php
http://example.com/press/feed/atom/
http://example.com/press/wp-admin/
http://example.com/press/feed/rss/
http://example.com/blacklist.dat
http://example.com/press/feed/
http://example.com/blackhole/

http://example.com/mint/pepper/orderedlist/downloads/download.php?file=
http://example.com/press/wp-content/online/code/test-file.text
http://example.com/press/2007/06/12/blackberry-curve-as-bluetooth-modem-for-mac/
http://example.com/press/wp-content/online/code/excerpt-reloaded-edits.txt
http://example.com/press/wp-content/online/code/skeleton+.css
http://example.com/minimalist.php
http://example.com/press/dungeon/
http://example.com/press/

That’s all folks..

Alright, my brain is rattling around so it’s time for a break. Hopefully you found something useful ;)