.. Your Daily Design Dosis

15+ Fresh and Useful WordPress Hacks / Code Snippets

| 5 Comments

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.

 

A good and huge collection of code snippets allows you to add some additional functionality to your WordPress Theme which is not offered by WordPress as by default. The ability to just ‘copy-and-paste’ these code snippets, as and when extra functionality is needed, makes WordPress one of the most used open source CMS of the world.

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.

I have made a selection of code recipes for adding more functionality which you just need to copy and paste when a specific functionality is needed. In case you liked these wordpress code snippets, make sure to check some more articles loaded with WordPress code snippets! Enough of the small talk, .. let’s rock ‘n’ roll, baby!

 

Embed a Page inside a Page

Paste the code below within the loop. Make sure to update page ID on line 1

<?php $recent = new WP_Query("page_id=**ID**"); 
while($recent->have_posts()) : $recent->the_post();?>
       <h3><?php the_title(); ?></h3>
       <?php the_content(); ?>
<?php endwhile; ?>

Source

 

Add Shortcut Links to the Toolbar

As with many things, WordPress makes it easy to customize the Toolbar, using the add_node() functions. In this recipe, I’m going to show you how to add a shortcut to WordPress toolbar. Paste the code below into your functions.php file.

// add a link to the WP Toolbar
function custom_toolbar_link($wp_admin_bar) {
	$args = array(
		'id' => 'gmail',
		'title' => 'Gmail', 
		'href' => 'https://mail.google.com/mail/#inbox', 
		'meta' => array(
			'class' => 'gmail', 
			'title' => 'sales@digwp.com'
			)
	);
	$wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'custom_toolbar_link', 999);

Once done, edit the code (see source to read exactly what you need to change), then save the file

Source

 

Add custom post types to archives page

Add this snippet into functions.php file.It will let you add custom post types to archives page

function add_custom_types_archive( $query ) {
if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
$query->set( 'post_type', array( 'post', 'your-custom-post-type-here'
            ));
      return $query;
    }
}

add_filter( 'pre_get_posts', 'add_custom_types_archive' );

Source

 

Embed and share Github gists on your WordPress blog

Github gists are a great way to create and share code snippets, and many developers are using Github. Today, I’m exited to share this very handy code snippet which allow you to embed a Github gist on your blog, simply by pasting the gist url.

Paste the following code into your functions.php file. Once done, simply paste the URL of a Github gist into a post or page. The gist will be automatically embedded in your blog.

**
 * Usage:
 * Paste a gist link into a blog post or page and it will be embedded eg:
 * https://gist.github.com/2926827
 *
 * If a gist has multiple files you can select one using a url in the following format:
 * https://gist.github.com/2926827?file=embed-gist.php
 */
wp_embed_register_handler( 'gist', '/https:\/\/gist\.github\.com\/(\d+)(\?file=.*)?/i', 'wp_embed_handler_gist' );

function wp_embed_handler_gist( $matches, $attr, $url, $rawattr ) {

	$embed = sprintf(
			'<script src="https://gist.github.com/%1$s.js%2$s"></script>',
			esc_attr($matches[1]),
			esc_attr($matches[2])
			);

	return apply_filters( 'embed_gist', $embed, $matches, $attr, $url, $rawattr );
}

Source

 

Display pingbacks/trackbacks count within admin post columns

By default, the post list in your WordPress dashboard, displays the comment count, but no trackback & pingback count. Here is a cool hack to add pingbacks/trackbacks count as well.

Simply paste the code below in your functions.php file. Once saved, your pingback/trackback count is displayed within admin post columns.

function commentCount($type = 'comments'){
	if($type == 'trackbacks'):
		$typeSql = 'comment_type = "trackback"';
		$oneText = 'One :trackback';
		$moreText = '% :trackbacks';
		$noneText = 'No :trackbacks';
	elseif($type == 'pingbacks'):
		$typeSql = 'comment_type = "pingback"';
		$oneText = 'One :pingback';
		$moreText = '% :pingbacks';
		$noneText = 'No :pingbacks';
	endif;
	global $wpdb;
    $result = $wpdb->get_var('
        SELECT
            COUNT(comment_ID)
        FROM
            '.$wpdb->comments.'
        WHERE
            '.$typeSql.' AND
            comment_approved="1" AND
            comment_post_ID= '.get_the_ID()
    );
	if($result == 0):
		echo str_replace('%', $result, $noneText);
	elseif($result == 1):
		echo str_replace('%', $result, $oneText);
	elseif($result > 1):
		echo str_replace('%', $result, $moreText);
	endif;
}
add_filter('manage_posts_columns', 'posts_columns_counts', 1);
add_action('manage_posts_custom_column', 'posts_custom_columns_counts', 1, 2);
function posts_columns_counts($defaults){
    $defaults['wps_post_counts'] = __('Counts');
    return $defaults;
}
function posts_custom_columns_counts($column_name, $id){
	if($column_name === 'wps_post_counts'){
		commentCount('trackbacks'); echo "<br />";
		commentCount('pingbacks');
          }
}

Source

 

Wordpress hacks

 

.htaccess Gzip Compression

Add the following code in your .htaccess file. Gzip will drastically reduce HTTP response time.

# BEGIN GZIP
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
# END GZIP

Source

 

Create a custom database error page

As a WordPress user, you probably had the infamous “Error establishing a database connection” error at least once. This error occurs when your database can’y handle a request. On cheap hosts, this can happen often. Today, I’m showing you how to give a custom style to this error page.

Paste the code below into a new file. Name it db-error.php and save it on your wp-contentdirectory. In case of a database error, WordPress will automatically use this file.

<?php // custom WordPress database error page

  header('HTTP/1.1 503 Service Temporarily Unavailable');
  header('Status: 503 Service Temporarily Unavailable');
  header('Retry-After: 600'); // 1 hour = 3600 seconds

  // If you wish to email yourself upon an error
  // mail("your@email.com", "Database Error", "There is a problem with the database!", "From: Db Error Watching");

?>

<!DOCTYPE HTML>
<html>
<head>
<title>Database Error</title>
<style>
body { padding: 20px; background: red; color: white; font-size: 60px; }
</style>
</head>
<body>
  You got problems.
</body>
</html>

Source

 

Remove unneeded thumbnails

Adding some or all of these lines of code to the functions.php of your wordpress theme will effectively remove some of the default images sizes that may be unneeded.

update_option( 'thumbnail_size_h', 0 );
update_option( 'thumbnail_size_w', 0 );
update_option( 'medium_size_h', 0 );
update_option( 'medium_size_w', 0 );
update_option( 'large_size_h', 0 );
update_option( 'large_size_w', 0 );

Source

 

Add PayPal Donate Button

Add this snippet to the functions.php to add ‘Donate’ Button on your WordPress Website

// paypal donate button
function cwc_donate_shortcode( $atts ) {
    extract(shortcode_atts(array<(<
        'text' => 'Make a donation',
        'account' => 'REPLACE ME',
        'for' => '',
    , $atts));

    global $post;<

    if (!$for) $for = str_replace(" ","+",$post->post_title);

    return '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation+for+'.$for.'">'.$text.'</a>';
}

add_shortcode('donate', 'cwc_donate_shortcode');

Source

 

Add a “delete” button to WordPress admin bar

he admin bar is a featured introduced by WordPress 3.1. It adds useful options such as adding new posts or editing an existing one. But it do not feature a “delete” button, so you can’t trash a post without accessing the post lists on the dashboard. Here is a cool hack to add a “delete” button to WordPress admin bar. To apply this tip, simply paste the following code into your functions.php file:

<?php
function fb_add_admin_bar_trash_menu() {
  global $wp_admin_bar;
  if ( !is_super_admin() || !is_admin_bar_showing() )
      return;
  $current_object = get_queried_object();
  if ( empty($current_object) )
      return;
  if ( !empty( $current_object->post_type ) &&
     ( $post_type_object = get_post_type_object( $current_object->post_type ) ) &&
     current_user_can( $post_type_object->cap->edit_post, $current_object->ID )
  ) {
    $wp_admin_bar->add_menu(
        array( 'id' => 'delete',
            'title' => __('Move to Trash'),
            'href' => get_delete_post_link($current_object->term_id)
        )
    );
  }
}
add_action( 'admin_bar_menu', 'fb_add_admin_bar_trash_menu', 35 );
?>

Source

 

Display RSS feeds on your WordPress blog

Do you ever wanted to be able to display any rss feed on your WordPress blog? If yes, here’s a simple code that will do the job without using the deprecated wp_rss() function. The following code have to be pasted wherever you want to display the feed. Don’t forget to update the feed url on line 3. Number of items to be displayed can be defined on line 6.

<?php
include_once(ABSPATH . WPINC . '/rss.php');
$feed = 'http://example.com/feed/';
$rss = fetch_feed($feed);
if (!is_wp_error( $rss ) ) :
    $maxitems = $rss->get_item_quantity(3);
    $rss_items = $rss->get_items(0, $maxitems);
    if ($rss_items):
        echo "<ul>\n";
        foreach ( $rss_items as $item ) :
            echo '<li>';
            echo '<a href="' . $item->get_permalink() . '">' . $item->get_title() . "</a>\n";
            echo '<p>' . $item->get_description() . "</li>\n";
        endforeach;
        echo "</ul>\n";
    endif;
endif;
?>

Source

 

Automatically add a class to body_class if there’s a sidebar

By default, the body_class() function adds some class to the <body> tag to allow you to style your site more easily. But unfortunely, no extra class is added when your template has a sidebar. Here is a imple function to solve this problem. To apply the hack, just paste the code below into your functions.php file.

function wpfme_has_sidebar($classes) {
    if (is_active_sidebar('sidebar')) {
        // add 'class-name' to the $classes array
        $classes[] = 'has_sidebar';
    }
    // return the $classes array
    return $classes;
}
add_filter('body_class','wpfme_has_sidebar');

Source

 

Redirect to single post page if there is one post in category/tag

If there is only one post in a category/tag, then when someone clicks on the category/tag link, it will take them directly to the full post instead of taking them to the category page (where there will only be one result).

To achieve this we will use wp_redirect which is a great feature for contexual template redirections. Here is the code to put in your functions.php file to jump single post archives :

function stf_redirect_to_post(){
 global $wp_query;
 // If there is one post on archive page
 if( is_archive() && $wp_query->post_count == 1 ){
 // Setup post data
 the_post();
 // Get permalink
 $post_url = get_permalink();
 // Redirect to post page
 wp_redirect( $post_url );
 }
 } add_action('template_redirect', 'stf_redirect_to_post');

Source

 

Automatically create meta description from content

By default, WordPress does not add a <meta description> tag to your blog. While not necessary, some SEO experts insists that this tag is important for your site SEO. So what about generating one using your post content? Here is a cool piece of code to do it easily. Paste the following code into your functions.php file:

function create_meta_desc() {
    global $post;
if (!is_single()) { return; }
    $meta = strip_tags($post->post_content);
    $meta = strip_shortcodes($post->post_content);
    $meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
    $meta = substr($meta, 0, 125);
    echo "<meta name='description' content='$meta' />";
}
add_action('wp_head', 'create_meta_desc');

Source

 

How to show an urgent message in the WordPress admin area

When writing custom WordPress theme or plugins, you might want to inform users that something important needs doing, perhaps due to an upgrade. e.g. You need the user to update a setting, or check that their settings have been transposed correctly. Here is a ready to use hook to display a custom message to admins.

function showMessage($message, $errormsg = false){
	if ($errormsg) {
		echo '<div id="message">';
	} else {
		echo '<div id="message">';
	}

	echo "<p><strong>$message</strong></p></div>";
}  

function showAdminMessages() {
    showMessage("You need to upgrade your database as soon as possible...", true);

    if (user_can('manage_options') {
       showMessage("Hello admins!");
    }
}

add_action('admin_notices', 'showAdminMessages');

Source

 

Add post thumbnails to RSS feed

This very cool piece of code will get the post thumbnail and automatically add it to your RSS feeds. Paste the code into functions.php and save the file. Don’t forget that you need to use a theme that supports post thumbnails for this snippet to work.

function cwc_rss_post_thumbnail($content) {
    global $post;
    if(has_post_thumbnail($post->ID)) {
        $content = '<p>' . get_the_post_thumbnail($post->ID) .
        '</p>' . get_the_content();
    }

    return $content;
}
add_filter('the_excerpt_rss', 'cwc_rss_post_thumbnail');
add_filter('the_content_feed', 'cwc_rss_post_thumbnail');

Source

 

Remove comments autolinks

If someone leaves a comment containing a url on your WordPress blog, the url will be automatically transformed to a link by WordPress. This can be useful, but personally I don’t like to see many links in comments, especially when they’re a bit spammy.
Removing autolinks is pretty easy: Just paste the following code into your functions.php file: Once you saved the file, you’ll notice that autolinks have disappeared.

remove_filter('comment_text', 'make_clickable', 9);

Source

 

Author: Gonzo the Great

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. I also speak about webdesign and branding in the Netherlands.

5 comments

on this article: “15+ Fresh and Useful WordPress Hacks / Code Snippets”
  1. Thanks for these tips, some are very useful especially the urgent message in the admin section, that’s helped be out heaps.

    Cheers

    • Hi EP,

      Yeah, I like that one too! Haven’t used it myself, but I added this one because it’s good to know you can inform a user that something important needs to be done, like updating a plugin or what so ever. I also see I forgot to mention that it should me pasted into your function.php .. but guess you guys figured that one out already ;-P

      Hope it turns out to be a great and useful hack, thanks for commenting! Cheers & Ciao!

  2. Fantastic and useful codes! gonna to try on my blog, i hope its works great.

    • Hi Guys,

      some of these hacks I manages to implement in some of the Themes I’ve worked on .. they should work in 3.0+ But as always, a word of warning: Backup your database and theme, so you can get everything back if and when it goes wrong! Enjoy your weekend, Cheers & Ciao!

  3. Hi there Dear, are you truly visiting this web site
    daily, if so after that you will absolutely take good experience.

top