WordPress Theme Tags Code Snippets

Between <head> and </head>

<html xmlns="<a href="http://www.w3.org/1999/xhtml%22">http://www.w3.org/1999/xhtml"</a> <?php
language_attributes(); ?>><head profile="<a href="http://gmpg.org/xfn/11%22">http://gmpg.org/xfn/11"</a>>
http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>;
charset=<?php bloginfo('charset'); ?>" />
bloginfo('name'); ?><?php wp_title(); ?></title>
name="description" content="<?php wp_title(); ?>" />
name="generator" content="WordPress <?php bloginfo('version'); ?>" />
<!-- leave this for stats please -->
<style type="text/css"
media="screen">@import url( <?php bloginfo('stylesheet_url'); ?>
	<link rel="alternate" type="application/rss+xml"
title="RSS 2.0" href="<?php bloginfo('rss2_url'); ?>" />
rel="alternate" type="text/xml" title="RSS .92" href="<?php
bloginfo('rss_url'); ?>" />
	<link rel="alternate"
type="application/atom+xml" title="Atom 0.3" href="<?php
bloginfo('atom_url'); ?>" />
	<link rel="pingback" href="<?php
bloginfo('pingback_url'); ?>" />
wp_get_archives('type=monthly&format=link'); ?>
//comments_popup_script(); // off by default ?>
<?php wp_head(); ?>

Styling Dierent Categories

<?php if ( is_category('15') ) {
	<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/cat-15.css"
type="text/css" media="screen" />;
<?php } else { ?>
	<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>"
type="text/css" media="screen" />
<?php } ?>

This snippet assigns a specic stylesheet (category-15.css) to category 15 and will assign the rest of the site the default stylesheet (style.css). Place this code in the <head> area.

Previous & Next Posts Links

<?php next_posts_link('Next Entries &raquo;') ?>
<?php previous_post_link('&laquo; Older Entries'); ?>

The first snippet will echo “Next Entries »” with a link to the next set of posts. The second snippet will echo “« Previous Entries” with a link to the previous set of posts. Place this code outside the loop.

First snippet will display a text “blog” with a link to the main page and second snippet will print WordPress pages links in a list (excluding the child pages and title header for the list). The active link from the list will be assigned with “current_page_item” class.

<?php if(have_posts()) : ?><?php while(have_posts()) : the_post(); ?>
<div class="post" id="post-<?php the_ID(); ?>">
<h1><a href="<?php the_permalink() ?>" rel="bookmark"
title="Permalink to <?php the_title(); ?>"><?php
<?php the_content(__('...read on »')); ?></div>
<?php endwhile; ?>
<?php else : ?>
<?php _e('Sorry, no posts matched your criteria.'); ?>
<?php endif; ?>

Unique Templates For Categories

$post = $wp_query- >post;
if ( in_category('3') ) {
include(TEMPLATEPATH . '/cat3.php’);
} elseif ( in_category('4') ) {
include(TEMPLATEPATH . '/cat4.php');
} else {
include(TEMPLATEPATH . '/cat.php');
} ? >

This snippet will assign a unique template to certain categories. In this case, ‘cat3.php’ will be assigned to ‘Category 3’, ‘cat4.php’ will be assigned to Category 4’, and the rest of the categories will be assigned ‘cat.php’. Place this code at the top of category.php

  1. Displays date and time. Format: January 21. 2007 More »
  2. Displays links to categories, each category separated by a comma (if more than one). More »
  3. Displays the URL to the post More »
  4. Displays or returns the title of the current post More »
  5. Displays the author of post More »
  6. Displays the ID of current post More »
  7. Displays a link to edit the current post More »
  8. Displays a list of Categories as links More »
  9. Displays a link to the next post More »
  10. Displays a link to the current post More »
  11. Displays links for next and previous pages More »
  12. Displays links for next and previous pages. More »
  13. All available monthly archives links displayed in an <li> Html list (by default). More
<?php if ( comments_open() ) : ?>
 <?php comments_popup_link( 'No comments yet', '1 comment', '% comments so far', 'comments-link', 'Comments are off for this post'); ?>
 <?php endif; ?>

This snippet helps you to hide the paragraph elements <p></p> that contains the comments_popup_link when comments are deactivated in the Write>Post screen. Good for those who want enable/disable comments post by post. Must be used in the loop.

Tags Cloud

<?php wp_tag_cloud('smallest=1&largest=9&'); ?>

This snippet will create a tag cloud, in alphabetical order, with the smallest text at 1 pt and the largest text at 9 pts.

Including templates

<?php get_header(); ?>
 <?php get_sidebar(); ?>
 <?php get_footer(); ?>
 <?php comments_template(); ?>
 <?php include (TEMPLATEPATH . '/yourfilename.php'); ?>

You can split your document into different files such as sidebar.php, header.php, footer.php or yourfilename.php and include theme to your template by adding above lines to your document.

<?php get_archives('postbypost', 8); ?>
 <?php bloginfo('rss2_url'); ?>
 <?php bloginfo('comments_rss2_url'); ?>
 <?php get_links('-1', '
	<li>', '</li>
', '', '', 'rand', '', '', '5'); ?>

1. Displays last 8 post titles
2. Displays RSS url for entries
3. Displays RSS url for comments
4. Display 5 of your blogroll links in a random turn

Show or display only child categories

You can display different categories on different places on your theme as well by using “show only children” snippet.

<?php wp_list_categories('use_desc_for_title=0&child_of=8'); ?>

Dont forget to replace ID of your category with 8

Unique Images For Dierent Categories

<?php if (is_category('7') ):
<img src='<?php bloginfo('template_url');?>/images/cat7.jpg' alt='' />
<?php } elseif (is_category('8') ):
<img src='<?php bloginfo('template_url');?>/images/cat8.jpg' alt='' />
<?php endif; ?>

This snippet assigns an image (cat7.jpg) next to each post title in category 7 and an image (cat8.jpg) next
to each post title in category 8. Place this code in the category.php file.

Show the Author

<h2>The Writer</h2>
 <span class="side_avatar"><?php echo get_avatar(get_the_author_email(), '40'); ?></span>
This <?=$tle?> was written by <strong><?php the_author(); ?></strong> on <?php the_time('l, F j, Y, G:i'); ?>. <strong><?php the_author_posts_link(); ?></strong> has written <strong><?php the_author_posts(); ?> posts</strong> on this blog.</div>

Showing Date

<div id="date"><?php print date('l jS F'); ?></div>

Listing Pages

<?php wp_list_pages('sort_column=menu_order&depth=1&title_li='); ?>

Showing RSS FEED

	<li class="feed"><a href="<?php bloginfo('rss2_url'); ?>">RSS Feed</a></li>

Most Viewed from lesterchan.net

<?php if (function_exists('get_most_viewed')): ?>
      <?php get_most_viewed(); ?></ul>
<?php endif; ?>

Post Tagged With

<h2>Posts Tagged &#8216;<?php single_tag_title(); ?>&#8217;</h2>

Site Page Links

	<li<?php if(is_home()) { ?> class="current_page_item"<?php } ?>><a href="
<?php bloginfo('home'); ?>">home</a></li>
<?php wp_list_pages('sort_column=menu_order&depth=1&title_li='); ?></ul>

This snippet will rst echo the text “home” with a link to the home page. Next, it will echo the WordPress
pages links in a list, in order dened by your settings, excluding the child pages, and excluding a title
header for the list. If one of the pages in the list is active, the link for that page will be assigned the class
“current_page_item”, which can now be styled in your CSS. Place this code in the template les.

Create Archive

<div class="archive">
<h2>Posts Tagged &#8216;<?php single_tag_title(); ?>&#8217;</h2>
<h2>Author Archive</h2>
<h2>Blog Archives</h2>

WP Show Recent Post Excerpt

<?php query_posts('showposts=1'); ?>
<?php while (have_posts()) : the_post(); ?>
<?php the_time('m.d.y') ?><?php the_excerpt(); ?>
<a href="<?php the_permalink() ?>" rel="bookmark">+More</a>
| <a href="/blog">+All Posts</a>
<?php endwhile; ?>

Show Latest Headlines

<?php query_posts('showposts=3&cat=6'); ?>
<?php while (have_posts()) : the_post(); ?>
	<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?></ul>

WP Custom Field Valu

<img src="/images/<?php $values = get_post_custom_values("key_name"); echo $values&#91;0&#93;; ?>" alt="" />

WordPress bookmarks

<div class="post-bookmarks">

New page template header



Template Name: Home page



Grab Category Name

This PHP snippet will get the category of the current post and place it in line where the code is inserted. It would be useful to add a heading or phrase that relates to the category.

<? $cat = get_the_category(); $cat = $cat&#91;0&#93;; echo $cat->cat_name;?>

Display Most Recent Twitter Entry


// Your twitter username.

$username = "TwitterUsername";

// Prefix - some text you want displayed before your latest tweet.

// (HTML is OK, but be sure to escape quotes with backslashes: for example href=\"link.html\")

$prefix = "";

// Suffix - some text you want display after your latest tweet. (Same rules as the prefix.)

$suffix = "";

$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";

function parse_feed($feed) {

$stepOne = explode("<content type=\"html\">", $feed);

$stepTwo = explode("</content>", $stepOne[1]);

$tweet = $stepTwo[0];

$tweet = str_replace(”<”, “<”, $tweet);

$tweet = str_replace(”>”, “>”, $tweet);

return $tweet;


$twitterFeed = file_get_contents($feed);

echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);


Display an External RSS Feed

<?php include_once(ABSPATH.WPINC.'/rss.php');

wp_rss('http://wpforums.com/external.php?type=RSS2', 5); ?>

Display Admin Section


<?php wp_register(); ?>
	<li><?php wp_loginout(); ?></li>
	<li><a href="http://www.wordpress.org/">WordPress</a></li>
<?php wp_meta(); ?>
	<li><a href="http://validator.w3.org/check?uri=referer">XHTML</a></li>

Display Recent Comments


global $wpdb;

$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,

comment_post_ID, comment_author, comment_date_gmt, comment_approved,


SUBSTRING(comment_content,1,30) AS com_excerpt

FROM $wpdb->comments

LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID =


WHERE comment_approved = '1' AND comment_type = '' AND

post_password = ''

ORDER BY comment_date_gmt DESC

LIMIT 10";

$comments = $wpdb->get_results($sql);

$output = $pre_HTML;

$output .= "\n

foreach ($comments as $comment) {

$output .= "\n

.":" . "<a href=\"" . get_permalink($comment->ID) .

"#comment-" . $comment->comment_ID . "\" title=\"on " .

$comment->post_title . "\">" . strip_tags($comment->com_excerpt)



$output .= "\n</ul>

$output .= $post_HTML;

echo $output;?>

Display Top Comment

<?php $result = $wpdb->get_results("SELECT
comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count
DESC LIMIT 0 , 10");

foreach ($result as $topten) {

$postid = $topten->ID;

$title = $topten->post_title;

$commentcount = $topten->comment_count;

if ($commentcount != 0) { ?>
	<li><a href="<?php echo get_permalink($postid); ?>"
title="<?php echo $title ?>"><?php echo $title
<?php } } ?>

Plugin for Pagenavigation from lesterchan.net

<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>

Showing first Picture from Post on the Frontpage

<?php $id =$post->ID;
$the_content =$wpdb->get_var("SELECT post_content FROM $wpdb->posts WHERE ID = $id");
$pattern = '!<img.*?src="(.*?)"!';
preg_match_all($pattern, $the_content, $matches);
$image_src = $matches&#91;'1'&#93;&#91;0&#93;; ?>

After these put following code to printing result

<img src="<?php if($image_src != '') { echo $image_src; } ?>"
alt="<?php the_title(); ?>" class="left" width="200px" height="200px" />

Display the First Image Attachment of a WordPress Post

$attachments = get_children(array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order'));
if ( ! is_array($attachments) ) continue;
$count = count($attachments);
$first_attachment = array_shift($attachments);
<?php echo wp_get_attachment_image($first_attachment->ID); ?>

Loading Javascript Libraries in WordPress generated page

<?php wp_enqueue_script('jquery'); ?>  

<?php wp_enqueue_script('jquery'); ?>

<?php wp_enqueue_script('newscript','/wp-content/plugins/someplugin/js/newscript.js',array('jquery'),'1.0' ); ?>

Load jQuery into WordPress generated pages, the wpenqueuescript function can be used in plugins as well. OR Add and load a new script that depends on jQuery (this will also cause it to load jQuery into the page as well).

Exclude Categories from RSS Feed

function myFilter($query) {
    if ($query->is_feed) {
        $query->set('cat','-5'); //Don't forget to change the category ID =^o^=
return $query;


Get the numeric ID of the category you want to exclude and edit the functions.php file in your theme. Code explanation. This hack works exactly the same way as the previous one: create a custom function to exclude the category that you don’t want to appear in your RSS feed, and then use the super-useful addfilter() function to apply it to the preget_posts() WordPress core function.

How to Wigetize a WordPress Theme

if ( function_exists(’register_sidebar’) )
<?php if ( !function_exists(’dynamic_sidebar’)
|| !dynamic_sidebar() ) : ?>

Edit functions.php and sidebar.php

Display Gravatars (WordPress 2.5+ Only)

<?php if(function_exists(’get_avatar’)){ echo get_avatar($comment, ‘50?);} ?>

Setting Up Auto-Discovery for Your WordPress Feeds

<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Comments Feed" href="<?php bloginfo('comments_rss2_url'); ?>" />
<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>" />

Shared login in WordPress

define('CUSTOM_USER_META_TABLE', 'wp_usermeta');

paste it in wp-config.php and make sure the prefixes are right (wp_* is default) also the blogs must be installed on the same database with different prefixes.

For example, you might have a primary blog with the table prefix wp_ on the database wordpressblog and you install a new blog on the same wordpressblog database but with a different prefix (this is important) – you can share the the primary blogs already populated user tables (in other words a shared login).

Llist feeds by category in wordpress

<?php wp_list_categories('feed_image=http://www.myblog.com/image.gif&feed=XML Feed&optioncount=1&children=0'); ?>

WordPress Current Page .current_page_item

<ul><li <?php if (is_page($post->ID)) { echo'class="current_page_item"'; } ?>>Menu Item 1</li></ul>

Show WordPress Post Attachments

// place inside loop
$args = array(
	'post_type' => 'attachment',
	'numberposts' => null,
	'post_status' => null,
	'post_parent' => $post->ID
$attachments = get_posts($args);
if ($attachments) {
	foreach ($attachments as $attachment) {
		echo apply_filters('the_title', $attachment->post_title);
		the_attachment_link($attachment->ID, false);

Show a user picture in wordpress

// Mostrar imatge d'usuari

function foto_usuario($que_usuario){
	$blog_url = get_bloginfo('url');
	echo'<img class="foto" alt="' . $que_usuario . '" src="' .$blog_url . '/wp-content/themes/.../img/.../' .$que_usuario. '.jpg"  />';

Así de sencillo y básico… y para insertarlo donde necesito:

<?php foto_usuario('usuario'); ?>

Showing Spesific Category Post

<?php $temp_query = $wp_query; ?>
<?php query_posts('category_name=herecomeyourcategoryname&showposts=4'); ?>
<?php while (have_posts()) : the_post(); ?>
<UL and LI items going here>
<?php endwhile; ?>
<?php $wp_query = $temp_query; ?>

You can create a temporary query and call the category name and number of posts




4 thoughts on “WordPress Theme Tags Code Snippets

  1. Hey! I know this is kinda off topic however , I’d figured I’d ask.
    Would you be interested in exchanging links or maybe
    guest writing a blog article or vice-versa?

    My blog discusses a lot of the same topics as yours and
    I believe we could greatly benefit from each other. If you’re interested feel free to shoot me an e-mail. I look forward to hearing from you! Great blog by the way!

  2. Hey just wanted to give you a quick heads up and let you
    know a few of the images aren’t loading properly. I’m not sure why but I think
    its a linking issue. I’ve tried it in two different internet browsers and both show the same results.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s