.. Your Daily Design Dosis

10 Fresh and Useful WordPress Code Snippets

| 2 Comments

WordPress comes with standard functions but there are many plugins and code snippets/hacks to give your blog a different look and/or function(s). I have collected a couple of very useful code snippets you can use when a specific functionality is needed.

Having a collection of hacks and/or code snippets in your toolbox is very useful when developing WordPress Themes on a regular basis, depending on your needs you can make your WordPress blog more functional and dynamic with these code snippets. Not to mention the time you’ll save during the process of coding your theme.

All these code snippets should work in WordPress 3.0+, but as always a word of warning for you guys ..

Note: These hacks worked at the time they were published, but as new versions of WordPress are released, some may no longer work. Please backup your theme files before attempting any hacks so you can restore things if something goes wrong.

In case you like(d) these wordpress code snippets, make sure to check some more articles loaded with useful WordPress code snippets! Enough of the small talk, .. let’s rock!

Add a link to your original posts using RSS feed

Another useful way to fight back against content theft is to automatically insert a copyright notice with a backlink to the original post on each RSS item. That way, scrapers who use your RSS feed to publish your content on their own sites automatically will also publish your copyright notice and backlink!

Simply add the code below to your functions.php file. Copyright notice can be customized on line 4.

// add custom feed content
function add_feed_content($content) {
	if(is_feed()) {
		$content .= '<p>This article is copyright &copy; '.date('Y').'&nbsp;'.bloginfo('name').'</p>';
	}
	return $content;
}
add_filter('the_excerpt_rss', 'add_feed_content');
add_filter('the_content', 'add_feed_content');

Source

Detect a comments page on your WordPress blog

On WordPress dashboard, there’s an option to divide comments lists in sub pages. Unfortunately, there’s no built-in conditional tag to know if you’re currently on a comment page.

Simply put the following code anywhere on your theme files. If you’re on a comment page, the conditional statement will return true, so any code within brackets will be executed.

$cpage = get_query_var( 'cpage' );
if ( is_singular() && $cpage > 0 ){
    // Your code here
}

This code works on posts, pages, attachments as well as all custom post_types.

Source

Displaying Gravatar from User Email in WordPress Posts, Pages and Widgets

Now lets assume that you do have email address of a user and permission to use their gravatar on your site. But you don’t have them as a registered user on your site. Or that you want to display the gravatars of selected users in a post, page or a widget. To solve this problem add this code in your theme’s functions.php file.

function wpb_display_gravatar($atts) { 
extract( shortcode_atts( array(
		'wpb_user_email' => '',
	), $atts ) );
if ($wpb_user_email == '') { 
	global $current_user;
	get_currentuserinfo();
	$getuseremail = $current_user->user_email;
} else { 
        $getuseremail = $wpb_user_email;
}
	$usergravatar = 'http://www.gravatar.com/avatar/' . md5($getuseremail) . '?s=32';

	echo '<img src="' . $usergravatar . '" />';
} 

add_shortcode('wpb_gravatar', 'wpb_display_gravatar');

If you have specified an email address parameter in your shortcode, then it displays gravatar for the email address provided in the shortcode instead of the current user. This shortcode can be used in posts, pages, and widgets. To display the gravatar of the current user use this shortcode:

[wpb_gravatar]

To display the gravatar of a user email address use shortcode like this:

[wpb_gravatar wpb_user_email="john.smith@example.com"]

You can also add CSS by adding .wpb_gravatar class to your stylesheet. Like this:

.wpb_gravatar { 
padding: 3px;
margin: 3px;
background:#FFFFFF; 
border:2px solid #eee; 
}

Source

Page Sensitive Multi-Level Navigation

The mission was to display sub-pages of the current page you are on in the left nav and once you hit the bottom of the hierarchy to show pages which are parallel to that page within the same branch of the hierarchy.

<?php
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0&depth=1");
if ($children == "")
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0&depth=1");
?>
<ul>
<?php echo $children; ?>
</ul>
<?php endif; ?>

Of course you style to taste .. Used in conjunction with a standard WordPress top-navigation and breadcrumbs you can easily display page sensitive multi-level navigation for your super-complex multi-level site!

Source

wordpress-code-snippets

Directly include Typekit fonts on your WordPress theme

Typekit is a useful service which allow you to use countless different fonts on your website or blog. Assuming you don’t want to use the TypeKit plugin, here’s how to enqueue the scripts directly from your theme.

Edit the code below and update the .js file path on line 2. Then, simple paste it on your functions.php file.

function theme_typekit() {
    wp_enqueue_script( 'theme_typekit', '//use.typekit.net/xxxxxxx.js');
}
add_action( 'wp_enqueue_scripts', 'theme_typekit' );

function theme_typekit_inline() {
  if ( wp_script_is( 'theme_typekit', 'done' ) ) { ?>
  	<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<?php }
}
add_action( 'wp_head', 'theme_typekit_inline' );

Source

WordPress function to show a total share counter (FB, Twitter, G+)

Sharedcount.com is a useful website which allow you to get the total likes, shares, tweets, etc for a specific web page. Here’s a super handy function to display how many times a page has been liked/shared/tweeted on your blog.

Simply paste the following function where you want your counter to appear:

function social_shares() {
    $url = get_permalink( $post_id ); 
    $json = file_get_contents(&quot;http://api.sharedcount.com/?url=" .
rawurlencode($url));
    $counts = json_decode($json, true);
    $totalcounts= $counts[&quot;Twitter&quot;] + 
$counts[&quot;Facebook&quot;][&quot;total_count&quot;] +
$counts[&quot;GooglePlusOne&quot;];
    echo &quot;&lt;div&gt;$totalcounts Share&lt;/div&gt;&quot;;
}

Source

Bookmark (aka: Link) Shortcode

I wanted to use the built in WordPress admin link manager (now referred to as bookmarks) on a big site where links (especially external links) may occasionally change and be referred to in many places. Now I can manage my links in one place and by placing this snippet of code in the functions.php file I can use a shortcode to bring up any link by it’s id.

<?php

	// Add Bookmark shortcode

	// Usage: [bookmark linkid=8]
	// Returns: <a title="Extreme Web Design" href="http://www.extremewebdesign.biz/" target="_blank">Extreme Web Design</a>

	function bookmark_shortcode($atts, $content = null) {
		extract(shortcode_atts(array(
			'linkid' => '0'
		), $atts));
		$bookmark = get_bookmark($linkid);
		return '<a title="' . $bookmark->link_description . '" href="' . $bookmark->link_url . '" target="' . $bookmark->link_target . '">' . $bookmark->link_name . '</a>';
	}
	add_shortcode("bookmark", "bookmark_shortcode");

?>

Source

Make your search results unlimited

The fact that WordPress displays 10 posts by default on the search results page can be annoying. If you’d like to display unlimited search results on the same page, here’s an easy way to do it. In search.php, find the code below:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

Once you found it, replace it by this:

<?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

Source

Code Snippet to Create a Directory Within Uploads Folder

Here’s a code snippet that allows your plugin to create a new folder in the /uploads directory on activation. Could be useful if your plugin needs to allow imports or uploads and you want them stored in a separate directory.

function myplugin_activate() {
	$upload = wp_upload_dir();
    $upload_dir = $upload['basedir'];
    $upload_dir = $upload_dir . '/mypluginfiles';
    if (! is_dir($upload_dir)) {
       mkdir( $upload_dir, 0700 );
    }
}

register_activation_hook( __FILE__, 'myplugin_activate' );

Source

Featured Image Meta

Give users more control over how the featured image is displayed for individual posts. The obvious place to put these options are in the thumbnail metabox itself. Adding the option is fairly simple, you’ll just need to hook into the admin_post_thumbnail_html filter:

/* Add a checkbox to the featured image metabox */

add_filter( 'admin_post_thumbnail_html', 'theme_featured_image_meta');

function theme_featured_image_meta( $content ) {
	global $post;
	$text = __( "Don't display image on post.", 'textdomain' );
	$id = 'hide_featured_image';
	$value = esc_attr( get_post_meta( $post->ID, $id, true ) );
    $label = '<label for="' . $id . '"><input name="' . $id . '" type="checkbox" id="' . $id . '" value="' . $value . ' "'. checked( $value, 1, false) .'> ' . $text .'</label>';
    return $content .= $label;
}

This option will need to be sanitized and saved when the post is updated- like any other custom field in a metabox.

Source

 

Author: Jan Rajtoral

Jan Rajtoral AKA Gonzo the Great is the Founder of and Designer at gonzodesign, providing design services across the full spectrum of Brand Identity, Graphic Design, Print and Advertising Design & Website Design.

2 comments

on this article: “10 Fresh and Useful WordPress Code Snippets”
  1. Very useful, thanks for posting. The bookmark shortcode will be of particular use to me!

    • Hi Kev,

      glad to hear it was useful to you! And yeah, shortcodes are the bomb! I’m using more and more shortcodes lately, not only for client sites but also for theme development. Especially in combination with TinyMCE buttons, .. sweeeeeet!

      And I also like to thank you for tweeting this article, cheers buddy!

top