• Blog

    Latest from our Blog

  • Tools

    Our Favourite WP Tools

  • Hosting

    Recommended Web Hosts

  • Coupons

    Get great money off deals

  • Themes

    WordPress Theme Directory

  • Plugins

    WordPress Plugins Directory

  • Promote

    Your WordPress Product

Ive mentioned before abuot the importance of having an army of useful code snippets and functions you can use when coding your WordPress themes, I found this really cool website which lists loads of them so check it out. Today’s post is a roundup of some of the most handy ones I could find.

Pagination without a Plugin

This snippet creates a classic paging navigation like the one seen in WP-PageNavi, which give a better overview for the user. It’s easy to implement and gives you total control over the output. Add the following to your functions.php :

<!--?php function pagination($prev = '«', $next = '»') { global $wp_query, $wp_rewrite; $wp_query--->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
$pagination = array(
'base' => @add_query_arg('paged','%#%'),
'format' => '',
'total' => $wp_query->max_num_pages,
'current' => $current,
'prev_text' => __($prev),
'next_text' => __($next),
'type' => 'plain'
);
if( $wp_rewrite->using_permalinks() )
$pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );

if( !empty($wp_query->query_vars['s']) )
$pagination['add_args'] = array( 's' => get_query_var( 's' ) );

echo paginate_links( $pagination );
};
?>

Then add this to your theme within the loop :

<!--?php pagination('»', '«'); ?-->

You can use the following CSS to customise the look :

.page-numbers { font-size: 15px; }
.page-numbers.current { color: #222; }
.page-numbers .dots { letter-spacing: 1px }
a.page-numbers  { font-size: 14px; color: #3888ff; }

Limit Number of Words in the Excerpt

This snippet let’s you limit the allowed number of words used in the exerpt. Copy this code into your functions.php

<!--?php function limit_words($string, $word_limit) { // creates an array of words from $string (this will be our excerpt) // explode divides the excerpt up by using a space character $words = explode(' ', $string); // this next bit chops the $words array and sticks it back together // starting at the first word '0' and ending at the $word_limit // the $word_limit which is passed in the function will be the number // of words we want to use // implode glues the chopped up array back together using a space character return implode(' ', array_slice($words, 0, $word_limit)); } ?-->

Then add this to your theme within the loop, change 41 to the number of words you wish to use :

<!--?php echo limit_words(get_the_excerpt(), '41'); ?-->

Add custom post type to feed

If you’re using custom post types on your WordPress site, you have to manually add it to the main RSS feed. You can choose what post types you want to include by adding the custom post type to the array.

<!--?php function myfeed_request($qv) {     if (isset($qv['feed']) && !isset($qv['post_type']))         $qv['post_type'] = array('post', 'movies', 'actors');     return $qv; } add_filter('request', 'myfeed_request'); ?-->

Pull in the tags related to a category

This is a way to show all tags related to a category, without returning them in a list. This is a great way of adding more SEO, and kill some bounce rate.

Just make sure you change the name of your category where the category_name= starts. Use spaces if your category is named using more than one word.

Put this code where you want the tags to be displayed.

<!--?php $project_query = query_posts('category_name=Real estate marketing'); while (have_posts()) : the_post();     $posttags = get_the_tags();     if ($posttags) {         foreach($posttags as $tag) {             $all_tags_arr[] = $tag ---> name; //USING JUST $tag MAKING $all_tags_arr A MULTI-DIMENSIONAL ARRAY, WHICH DOES WORK WITH array_unique
        }
    }
endwhile;

$tags_arr = array_unique($all_tags_arr); //REMOVES DUPLICATES
foreach( $tags_arr as $tag ):
    $el = get_term_by('name', $tag, 'post_tag');
    $arr[] = '"tag-'.$el->slug.'"';
?>
<span> <span class="slash">, </span></span>
<!--?php endforeach; ?-->

Display user info

WordPress allows user to add information about themselves in their profile page in WP Admin. To display the users information, you can use this snippet.

<!--?php global $current_user; get_currentuserinfo(); $user_id = $current_user--->ID; // You can set $user_id to any users, but this gets the current users ID.

$user_twitter = get_user_meta( $user_id, 'twitter', true);
echo $user_twitter;
?>

Dynamic copyright text

This snippet allow you to create a cool copyright text for your footer. This is set to automatically update the date, using the the_date() function.

Just copy the snippet in to your footer.php.

(c) <!--?php echo date('Y'); ?-->
|
| <!--?php bloginfo('description'); ?-->

Highlight Current Page in Menu

It is always good to highlight the current page in navigation or side menu. WordPress menu functions (wp_nav_menu, wp_list_pages) automatically adds current_page_item class to li containing active link.

So it’s up to us to use the same class to highlight the current page.

/* Highlight using list element */
li.current_page_item{
	background:#999;
	color:#fff;
}

/* Highlight using link element */
li.current_page_item a{
	text-decoration:underline;
	background:#666;
}

Custom RSS Feed Footer

Place this in your functions.php file to easily add a custom text footer to your WordPress feed.

<!--?php if ( !function_exists('custom_feed_footer') ) { 	function custom_feed_footer($content) 	{ 		if(is_feed()) 		$content .= 'Your text'; 		return $content; 	} 	add_filter('the_excerpt_rss', 'custom_feed_footer'); 	add_filter('the_content', 'custom_feed_footer'); } ?-->

Pre-fill a Custom Menu

We know how to Add Custom Menus Support to our theme, to allow a THEME LOCATION of “main_nav” (for example), but what if you also want to automate the next steps of creating a Menu itself, setting the Theme Location to show that new Menu, and adding a Page to that new Custom Menu ?

We’ll start with the Add Custom Menus Support code to register a Menu Location of “The main menu” / “main_nav”, and take it that next couple steps by creating an actual Menu called “Main Menu”, adding a link titled ‘THIS WILL BE THE LINK TITLE’ linking to page id #1, and telling WP to set our new “Main Menu” as THE menu for the “main_nav” theme location.

<!--?php add_action( 'init', 'add_menus' ); function add_menus() { 	register_nav_menus( 		array( 			'main_nav' =--> 'The main menu',
		)
	);
	$new_menu_id = wp_create_nav_menu('Main Menu');
	$page_args = array(
		'menu-item-object-id' => 1,
		'menu-item-object' => 'page',
		'menu-item-parent-id' => 0,
		'menu-item-type' => 'post_type',
		'menu-item-title' => 'THIS WILL BE THE LINK TITLE',
		'menu-item-status' => 'publish',
	);
	if ( $new_menu_id > 0 ) {
		// set our new MENU up at our theme's nav menu location
		set_theme_mod( 'nav_menu_locations' , array( 'main_nav' => $new_menu_id ) );
		// add a menu item to that new menu
		wp_update_nav_menu_item( $new_menu_id , 0, $page_args );
	}
}
?>

Show Tag Cloud

The tag cloud function could be used all around the theme: sidebar, footer and everywhere else. It just returns simple links, which can be styled in any way. Wrap the function in div’s or paragraphs to have the desired styling.

<!--?php wp_tag_cloud(array(   'smallest' =--> 10,      // size of least used tag
  'largest' => 18,       // size of most used tag
  'unit' => 'px',        // unit for sizing
  'orderby' => 'name',   // alphabetical
  'order' => 'ASC',      // starting at A
  'exclude' => 6         // ID of tag to exclude from list
)); ?>

Include a Template Part

This snippet let’s you include any part of a template, saving you having to put the same code over and over in each file – you can create it once and include, name your file “filename.php” and use this where you want it to include :

<!--?php get_template_part( 'filename' ); ?-->

Increase memory limit

Allowed memory size of bytes exhausted. What is up with this?

WordPress has a built in memory limit to save you from badly written plugins that will eat up all your websites memory. The standard memory limit is set to 32MB, but it’s easy to increase. Just add the following in wp-config.php:

define('WP_MEMORY_LIMIT', '96M');

List all categories with posts

Add this to the template you want the list to appear.

Output:
Category Name 1
post title 1
post title 2
post title 3
Category Name 2
Post title 1

<!--?php //for each category, show all posts $cat_args=array(   'orderby' =--> 'name',
  'order' => 'ASC'
   );
$categories=get_categories($cat_args);
  foreach($categories as $category) {
    $args=array(
      'showposts' => -1,
      'category__in' => array($category->term_id),
      'caller_get_posts'=>1
    );
    $posts=get_posts($args);
      if ($posts) {
        echo '
Category: ' . $category->name.'

 ';
        foreach($posts as $post) {
          setup_postdata($post); ?>

          <!--?php         } // foreach($posts       } // if ($posts     } // foreach($categories ?-->

Comment Count Shortcode

Use this shortcode to display a specific post’s comment count. All you have to do is add the post ID.

Here is an example:
[comments id="1"]
This will display the comment count for the post with the ID of 1.

<!--?php function comments_shortcode($atts) { 	extract( shortcode_atts( array( 		'id' =--> ''
	), $atts ) );

	$num = 0;
	$post_id = $id;
	$queried_post = get_post($post_id);
	$cc = $queried_post->comment_count;
		if( $cc == $num || $cc > 1 ) : $cc = $cc.' Comments';
		else : $cc = $cc.' Comment';
		endif;
	$permalink = get_permalink($post_id);

	return '<a class="comments_link" href="'. $permalink . '">' . $cc . '</a>';

}
add_shortcode('comments', 'comments_shortcode');
?>

Once again, thanks to WP Snippets – go bookmark it now!


Post Tags

Author:

Oliver Dale is the founder of Kooc Media, a small internet company based in the UK. Kooc Media runs several high-profile websites including WPLift, ThemeFurnace and DesignersTalk.

Leave Yours +

30 Comments

  1. About displaying User Info: That information has to be set/stored, this can differ per theme. It took me two hours to figure out that a themes stored its is tb_twitter…

  2. Howdy! Whenever I see the word “include” or “require”, my brain alerts. The “Include any file” section is wrong. The get_template_part function *does* include a file, but not any file, and definitely not by the filename. If you’d like to include a file by its filename you can use include() or require(). 

    The get_template_part() function is designed to, as it says, give you a part of your template, it uses the locate_template() function to find the appropriate file in your theme or your parent theme. Like get_template_part( ‘sidebar’, ‘left’ ); will: 1. search for sidebar-left.php in your theme, 2. search for sidebar-left.php in your parent theme, 3. search for sidebar.php in your theme and finally 4. search for sidebar.php in your parent theme.

    This is a very convenient way to grab and reuse different parts of the template, though for standard things like header, footer, sidebar, there are other very similar functions — get_header, get_sidebar, get_footer. With get_template_part() you can get things like breadcrumbs.php, navigation.php or perhaps your content.php. You’ll see that in Twenty Eleven get_template_part() is used with get_post_format() to “try and load files like” content-quote.php, content-link.php, etc., and then fall back to content.php if they don’t exist.

    With get_template_part you can’t “include” things like ~/.ssh/id_rsa or ../../../wp-config.php so it’s more secure than just using include or require.

    Anyway, just spotted it in my reader and thought I’d come by to think out loud, hope that’s clear enough :)

    ~ K

    • Brilliant – Thanks for adding to that, Ive edited the post to explain that one a bit better :)

      • Cool! The Codex page does a very good job at explaining how it works: http://codex.wordpress.org/Function_Reference/get_template_part

      • I’ve been browsing online more than 4 hours today, yet I never found any interesting article
        like yours. It’s pretty worth enohgh for me. In my view, iif alll web oeners andd bloggers made good content as you did, thhe net will be much
        more useful than ever before.|
        I couldn’t resist commenting. Exceptionally well written!|
        I will right away take hold of your rss feed as I can not find your email
        subscription hyperlink or e-newsletter service. Do you’ve any?
        Kinmdly perdmit me recognise so that I may subscribe. Thanks.|
        It is perfect time to make ome plans for the future annd it’s time to be happy.

        I’ve read this post and if I could I desire to suggest you
        some interesting things or tips. Maybe you could write next articles referring to thjis
        article. I wish to read more things about it!|
        It’s perfect time to make a few plans for the future and it
        is time to be happy. I’ve learn this submit and if I could I wish to counsel yyou
        some fascinating things or suggestions. Perhaps you can write next articles relating to thos article.
        Idesire to learn more issuees approximately it!|
        I have been browsing online more than three hours today, but I never found
        any interesting article like yours. It’s lovely price
        sufficient for me. Personally, if all web owners and bloggers
        made just right content material as you probably did, the web can
        be much more useful than ever before.|
        Ahaa, its pleasant dialogue regarding this article here at
        this website, I have read all that, so now me also
        commenting here.|
        I am sure this post has touched all the internet people, its really really
        good post on building up new weblog.|
        Wow, this post is good, my sister is analyzing these kinds
        of things, so I am going to tell her.|
        Saved as a favorite, I really like your site!|
        Way cool! Some very valid points! I appreciate you writing this post and the rest of the
        website is also really good.|
        Hi, I do believe this is an excellent website.
        I stumbledupon it ;) I’m going to return once again since i have book-marked it.
        Money and freedom is the greatest way to change, may you be rich and conntinue to
        guide other people.|
        Woah! I’m really loving the template/theme of this
        blog. It’s simple, yet effective. A lot of tims it’s very difficult to get that “perfect balance”
        between user friendliness and visual appearance. I must say you’ve done a superb job with this.
        Additionally, the blog loads super quick for mee on Firefox.
        Exceptional Blog!|
        These are truly impressive ideas in concerning
        blogging. You have touched some nice points here. Any way keep up wrinting.|
        I really like whst you guys tend to be up too. Such clever
        work and exposure! Keep up the awesome woks guys I’ve added you guys to our blogroll.|
        Howdy! Someone in my Facebook group shared
        this website with us so I came to give it a look. I’m definitely enjoying the information.
        I’m bookmarking and will be tweeting this to my followers!
        Exceptional blog and terrific design and style.|
        I enjoy what you guys are usually up too. This kind of clever work and exposure!

        Keep up the good works guys I’ve inclded yoou guys to mmy own blogroll.|
        Hey there would you mind sharing which blog platform you’re
        using? I’m going to start my own blog in the near future
        but I’m having a difficult time choosing between BlogEngine/Wordpress/B2evolution
        and Drupal. The reason I ask is because your design
        seems different then most blogs and I’m looking for slmething unique.

        P.S My apologies for getting off-topic but I had to ask!|
        Hi would you mind letting me know which hosting company you’re using?
        I’ve loladed your blog in 3 different browsers and I must say this blog loads a lot fastrer then most.
        Can you recommend a good internet hostikng provider aat a
        honest price? Cheers, I appreciate it!|
        I love it when people get together and share opinions.

        Grea website, keep it up!|
        Thank you for the auspicious writeup. It in fact was a
        amusement account it. Look advanced to far added agreeable feom you!

        However, how can wwe communicate?|
        Hey there just wanted to give you a quick heads up. The words in your content seem to be running off the screen in Opera.
        I’m not sure if this is a format issue or something to do with browser compatibility
        but I thought I’d post to let you know. The design look great though!
        Hope you get the issue fixed soon. Kudos|
        This is a topic that is close to my heart…
        Thank you! Exactly where are your contact details though?|
        It’s very simple to find out any matter on net as compared to books,
        as I found this paragraph at this site.|
        Does your website have a contact page? I’m having trouble locating it but, I’d like to shoot you an email.

        I’ve got some ideas for your blog you might be interested in hearing.
        Either way, greaat site and I look forward to seeing itt expand over time.|
        Greetings! I’ve been following your web site for
        a long time now and finally got the bravery to go ahead and
        give you a shout out from New Caney Tx! Just wanted to mention keep up the great job!|
        Greetings from Colorado! I’m bored too death at work so I
        decided to browse your website on my iphone during lunch break.

        I really like thee information you present here and
        can’t wait to take a look when I get home. I’m surprised at hoow quickk your blog loaded on
        my cell phone .. I’m not even using WIFI, just 3G .. Anyways, fantastic site!|
        Its such as you read my mind! You seem to understand a lot about
        this, like you wrote the e-book in it or something. I feel that
        you simply can do with a few percent to drive the message home
        a bit, but instead of that, that is magnificent blog.
        An excellent read. I will definitely be back.|
        I visited various web sites however the audio quality for audio songs current at this site is actually wonderful.|
        Hello, i read your blog from time to time and i own a similar one
        and i was just wondering if you get a lot of spam remarks?
        If so how do you stop it, any plugin or anything you can advise?
        I get so much lately it’s driving me mad so any support is very much appreciated.|
        Greetings! Very useful advice within this post! It is thhe little chqnges
        that will make the greatest changes. Many thanks for sharing!|
        I really lokve your website.. Excellejt colors & theme.
        Did you make thuis amazing site yourself? Please reply back aas I’m hoping to
        create my own blog and would like to find out where you got this from or just
        what the theme is called. Kudos!|
        Hello there! This blog post couldn’t bbe written any better!
        Going through thijs article reminds me of my previous roommate!
        He constantly kept talking bout this. I most certainly will send this information to him.
        Fairly certain hee will have a great read. Thank you for sharing!|
        Wow! This blog looks exactly like my old one! It’s on
        a completely different topic but it has pretty much
        the same layout and design. Excellent choice of colors!|
        There’s definately a lot too learn about this subject. I really lile all the points you made.|
        You made some good points there. I checked on the nett to llearn more about the issue and found most
        individuals will goo along with your views on this web site.|
        What’s up, I read your blogs like every week. Your writing
        style is awesome, keep doing what you’re doing!|
        I simply couldn’t depart your web site prior to suggesting that
        I extremely enjoyed the standard info a person provide
        to your visitors? Is gonna be back regularly in order to
        check out new posts|
        I need to to thank you for this good read!! I absolutely enjoyed every little bit of it.
        I have got you saved as a favorite to check out new things
        you post…|
        Hello, just wanted to mention, I liked this post.
        It was helpful. Keep on posting!|
        I drop a leave a response each time I especially enjoy a article on a
        site or if I have something to valuable to contribute to the conversation.
        Usually it’s a result of tthe sincerness communicated inn the
        article I looked at. And onn this post Handy WordPress Code Snippets forr Yourr Themes Part 2 – WPLift.

        I waas actually moved enough to drop a comment ;) I do have some questions for you if it’s allright.
        Could it be just me or does it look like like some of
        the remarks appear like they are coming from brain
        dead visitors? :-P And, if you are writing on additional online sites, I would like
        to follow you. Could you make a list the complete urls of your shared
        pages like your linkedin profile, Facebook page or twitter feed?|
        Hi there, I enjoy reading through your article post.

        I like to write a little comment to support you.|
        I constantly spent my half an hour to read this website’s posts all
        the time along with a mug of coffee.|
        I always emailed this web site posst page to all myy contacts, as if like to read
        it next my contacts will too.|
        My programmer is trying to convince me to move to .net
        from PHP. I have always disliked the idea because of the costs.
        But he’s tryiong none the less. I’ve been
        using Movable-type on a variety of websites for aout a year annd amm woreied about
        switching to another platform. I have heard great things about blogengine.net.
        Is there a way I can import all my wordpress posts into it?
        Any kind of help would be greatly appreciated!|
        Howdy! I could have sworn I’ve visited this blog
        before but after going through some of the posts I realized it’s new
        to me. Anyways, I’m definitely pleased I stumbled upon it
        and I’ll be book-marking it and checking back frequently!|
        Terrific article! That is the type of infoormation that shoujld be shared
        around the net. Shame on the seek engines for now not positioning this submit upper!

        Come on over and consult with mmy site . Thanks =)|
        Heya i am for the first time here. I found this board and I find It rewlly useful & it helped me out much.
        I hoppe to give something back and help others like you helped me.|
        Hi, I do believe your web site could be having
        web browser compatibility issues. When I take a look at your
        blog in Safari, itt looks fine however, when opening in I.E., it’s got some overlapping issues.
        I merely wanted to give you a quick heads up! Besides that, great website!|
        Someone essentially assist to make critically articles I
        would state. That is the first time I frequented your web page and so far?
        I surprised with the analysis you made to create this particular put up amazing.
        Magnificent activity!|
        Heya i am for the primary time here. I came across this board and I
        in finding It truly useful & it helped me out much. I am hoping to give something back and
        help others like you helped me.|
        Hi! I simply want to offer you a big thumbs up for the great information you have here on this post.
        I will be returning to your web site for more soon.|
        I always used to study post in news papers but now as I am a user
        of internet therefore from now I am using net for
        posts, thanks to web.|
        Your method of explaining the whole thing in this piece of writing is in
        fact nice, all can without difficulty know it,
        Thanks a lot.|
        Hello there, I found your site by means of Google at the same time
        as looking for a related matter, your site got here up,
        it seems good. I have bookmarked it in my google bookmarks.

        Hello there, just became aware of your weblog via
        Google, and found that it’s truly informative. I am gonna be
        careful for brussels. I will appreciate when you proceed this in future.
        Numerou folks will be benefited outt of your writing. Cheers!|
        I’m curious to find out what blog system you are working with?

        I’m having some smll security issues with my latest websjte and I’d like to find something
        more safeguarded. Do you have any suggestions?|
        I am really impressed with your writing skills and
        also with the layout on your blog. Is this a paid theme or did you modify
        it yourself? Either way keep up the excellent quality writing, it’s rare to see a
        nice blog like this onne today.|
        I’m really inspired with your writing skills as neatly as with the structure for your blog.
        Is that this a paid subject or did you modify it yourself?
        Anyway stay up the nice quality writing, it is rare
        to peer a great weblog like this one nowadays..|
        Hi, Neat post. There is an issue with your web site in internet explorer, may check this?
        IE nonetheless is the market leader and a huge part of other folks will pass over your
        excellent writing because of this problem.|
        I’m not sure where you’re getting your info, but good topic.
        I needs to spend some time learning much more or understanding
        more. Thanks for great information I was looking for this info for my mission.|
        Hi, i think that i saw you visited my blog so i came to “return
        the favor”.I am attempting to find things to enhance my site!I suppose its
        ok to use a few of your ideas!!
        \

      • I really like your blog.. very nice colors & theme.
        Did you make this website yourself or did you hire someone to do it for you?
        Plz respond as I’m looking to design my own blog and would like
        to find out where u got this from. kudos

  3. Thanks for the coding here!

  4. Thanks for the coding here!

  5. Thanks for the coding here!

  6. Pushpinder Bagga

    Thanks mate – I liked the template part tip

  7. The get_template_part() function is designed to, as it says, give you a
    part of your template, it uses the locate_template() function to find
    the appropriate file in your theme or your parent theme. Like
    get_template_part( ‘sidebar’, ‘left’ ); will: 1. search for
    sidebar-left.php in your theme, 2. search for sidebar-left.php in your
    parent theme, 3. search for sidebar.php in your theme and finally 4.
    search for sidebar.php in your parent theme. The Codex page does a very good job at explaining how it.

    Anyway, just spotted it in my reader and thought I’d come by to think out loud, hope that’s clear enough :) thanks for shearing!

  8. Very nice post and  I admire your efforts in putting together this impressive informative post. This is great piece of coding that helps me a lot. Thank you so much for sharing this

  9. This is a really nice article. I am sure a lot of people
    will benefit from it. Thanks 

  10. Very useful snippets, Thanks ;)

  11. This is really interesting, You are a very skilled blogger.
    I have joined your feed and look forward to seeking more of your excellent post.
    Also, I’ve shared your website in my social networks!

  12. Hello Dear, are you truly visiting this web site regularly,
    if so after that you will definitely obtain good know-how.

  13. I love to disseminate understanding that will I have accumulated through the season to assist enhance
    team efficiency.

  14. I have гead a few just right stuff here. Definitely value bookmarkiոg for revisiting.

    I աonder how muϲh effort yoս place to make this
    sort of great iոformative site.

  15. Found some handy snippets. Thanks. I grabbed one for my pool at http://www.wpcustoms.net – credit link is set :)

  16. Very quickly this website will be famous among all blog visitors, due to it’s fastidious articles or reviews

  17. Excellent post. I was checking constantly this blog and I’m impressed!
    Very helpful information specially the last part :)
    I care for such info a lot. I was seeking this certain information for a very long time.
    Thank you and good luck.

Leave a Reply

* Required Fields.
Your email will not be published.

Search

Our Sponsors