Top Website Designing: Call:-+91-9582929295(India) or +1-917-310-3767(US)

Handy WordPress Code Snippets for Your Themes Part 2

Home
Wordpress
Handy WordPress Code Snippets for Your Themes Part 2

Handy WordPress Code Snippets for Your Themes Part 2

By There are no tags 0 comments

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!

Related posts:

  1. 15 Free WordPress Business & Corporate Themes 2012 (Part 3) Business themes continue to be one of the biggest areas...
  2. 40 Premium WordPress Business & Corporate Themes Part 4 Business themes continue to be big business for WordPress theme...
  3. A History of Default WordPress Themes WordPress has come a long way since its first release...
  4. Including content in WordPress posts using custom shortcodes Often when you’re promoting a product or service, you’ll have...
  5. 25 WordPress Real Estate Themes for 2012 The real estate market is one that has long embraced...
Top website Designing Company in India
About The Author

There are no comments yet, but you can be the first



Leave a Reply



Follow Us!

Search

Post requirement / Ask for Support!

Do you have question related to website designing, graphic designing or need any technical support, feel free to contact us. Contact us at mail@topwebsitedesigning.com or call +91-9582929295. You can also skype me on "s.goel1"
Contact +91-9582929295, +91-9266229292

ad