WP-Mix

A fresh mix of code snippets and tutorials

Random WordPress Snippets

Just a collection of miscellaneous & random WordPress snippets for your enjoyment.

Display Random Posts

Display Random Posts:

<?php query_posts(array('orderby' => 'rand', 'category_name' => Services, 'showposts' => 1)); 
if (have_posts()) : while (have_posts()) : the_post(); ?>
	<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
	<?php the_excerpt(); ?>
 <?php endwhile; ?>
 <?php endif;?>

Display Latest Posts

Display Latest Posts:

<?php query_posts('category_name=wordpress&showposts=1'); 
if (have_posts()) : while (have_posts()) : the_post(); ?>
	<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
	<?php the_excerpt(); ?>
 <?php endwhile; ?>
 <?php endif;?>

Display All Posts

Display All Posts:

<?php $first_post = 0; ?>
<?php while(have_posts()) : the_post(); ?>
	<?php $myposts = get_posts('numberposts=-1&offset=$first_post');
	foreach($myposts as $post) : ?>			
 
		<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
		<?php the_excerpt(); ?>
 
	<?php endforeach; ?>
<?php endwhile; ?>

Display posts from a Featured category

Display posts from a Featured category:

<?php if (have_posts()) : while (have_posts()) : the_post();
	$customField = get_post_custom_values('featured');
	if (isset($customField[0])) {
		the_title();
		the_excerpt();
	}
	endwhile;
endif; ?>

Get custom fields outside the loop

Get custom fields outside the loop:

<?php global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'customField', true); ?>

Recent Posts by category

Recent Posts by category:

<?php if (is_single()) :
	global $post;
	$categories = get_the_category();
	foreach ($categories as $category) : 
		$posts = get_posts('numberposts=5&exclude='.$GLOBALS['current_id'].'&category='.$category->term_id);
		if(count($posts) > 1) { ?>

			<div class="widget">
				<h3>More posts in <?php echo $category->name; ?></h3>
				<ul>
					<?php foreach($posts as $post) : ?>
					<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
					<?php endforeach; ?>
				</ul>
			</div>

		<?php } ?>
	<?php endforeach; ?>
<?php endif; ?>

Related posts based on tag

Related posts based on tag:

<?php $tags = wp_get_post_tags($post->ID);
if ($tags) {
	$tag_ids = array();
	foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
	$args=array(
		'tag__in' => $tag_ids,
		'post__not_in' => array($post->ID),
		'showposts' => 5, // display this many posts
		'caller_get_posts' => 1
	);
	$my_query = new wp_query($args);
	if($my_query->have_posts()) { ?>
		<h3>Related Posts</h3>
		<ul>
			<?php while ($my_query->have_posts()) { $my_query->the_post(); ?>
			<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to < ?php the_title_attribute(); ?>">< ?php the_title(); ?></a></li>
			<?php } ?>
		</ul>
	<?php }
} ?>

Display Popular Posts

Display Popular Posts:

<h3>Popular Posts</h3>
<ul>
	<?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->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) { ?>
		<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>"><?php echo $title ?></a> (<?php echo $commentcount ?>)</li>
		<?php }
	} ?>
</ul>

Login form that returns user to current page

Login form that returns user to current page:

<?php if(!is_user_logged_in()) { ?>

	<form action="<?php echo wp_login_url(get_permalink()); ?>" method="post">
		<label for="log"><input type="text" name="log" id="log" value="<?php echo wp_specialchars(stripslashes($user_login), 1) ?>" size="22" /> User</label>
		<label for="pwd"><input type="password" name="pwd" id="pwd" size="22" /> Password</label>
		<input type="submit" name="submit" value="Send" class="button" />
		<label for="rememberme"><input name="rememberme" id="rememberme" type="checkbox" checked="checked" value="forever" /> Remember me</label>
	</form>

<?php } ?>

Customize the Password Form

Customize the Password Form:

<?php function customize_password_form() {
	global $post;
	$label = 'pwbox-'.(empty($post->ID) ? rand() : $post->ID);
	$output = '<form action="' . get_option('siteurl') . '/wp-pass.php" method="post">
				<p>' . __("This post is password protected. Request a password:") . '</p>
				<p>
					<label for="' . $label . '">' . __("Password") . ' 
						<input name="post_password" id="' . $label . '" type="password" size="20" />
					</label>
					<input type="submit" name="Submit" value="' . esc_attr__("Submit") . '" />
				</p>
			</form>';
	return $output;
}
add_filter('the_password_form', 'customize_password_form'); ?>

Display custom number of posts

Display custom number of posts:

<?php function custom_posts_per_page(&$q) {
	if ($q->is_category)
	$q->set('posts_per_page', 7);
	// $q->is_year;
	// $q->is_author;
	// $q->is_search;
	return $q;
} 
add_filter('parse_query', 'custom_posts_per_page'); ?>

Include Canonical URLs for comments

Include Canonical URLs for comments:

<?php function canonical_for_comments() {
	global $cpage, $post;
	if ($cpage > 1) : ?>
		<link rel="canonical" href="<?php get_permalink($post->ID); ?>" />
	<?php endif;
}
add_action('wp_head', 'canonical_for_comments'); ?>

Basic Browser Detection

Basic Browser Detection:

<?php function browser_body_class($classes) {
	global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
	if($is_lynx) $classes[]       = 'lynx';
	elseif($is_gecko) $classes[]  = 'gecko';
	elseif($is_opera) $classes[]  = 'opera';
	elseif($is_safari) $classes[] = 'safari';
	elseif($is_chrome) $classes[] = 'chrome';
	elseif($is_IE) $classes[]     = 'ie';
	else $classes[]               = 'other';
	if($is_iphone) $classes[]     = 'iphone';
	return $classes;
}
add_filter('body_class','browser_body_class'); ?>

This will output the corresponding browser name as a class to the <body> tag, like so:

<body class="home blog logged-in safari">

Add/remove contact fields for registered users

Add/remove contact fields for registered users:

<?php function customize_contact_methods($contactmethods) {

	// add these
	$contactmethods['twitter'] = 'Twitter <span class="description">(username)</span>';
	$contactmethods['facebook'] = 'Facebook <span class="description">(username)</span>';
	$contactmethods['linkedin'] = 'LinkedIn <span class="description">(profilename)</span>';
	$contactmethods['flickr'] = 'Flickr <span class="description">(profilename)</span>';

	// remove these
	unset($contactmethods['yim']);
	unset($contactmethods['jabber']);
	return $contactmethods;
}
add_filter('user_contactmethods', 'customize_contact_methods', 10, 1); ?>

Note: any added custom contact fields are available using get_the_author_meta().

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress