Blog, WordPress, WordPress Snippet Codes

WordPress Code Snippets

WordPress code snippets are useful for improving WordPress website appearance and increasing performance and security. Codes are useful for webmasters.

How to Prevent Direct Access to PHP File in WordPress

Sometimes hackers want to access PHP files and use the for there benefits. To prevent direct access, add code below to your files.

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.

It should be the first code in PHP file.

Allow Contributors to Upload Images in WordPress

By default, WordPress does not permit contributor accounts to upload images. This particular code snippet allows contributor accounts to upload images to their articles.

Add this below code in the functions.php file of your theme:

if(current_user_can('contributor') && !current_user_can('upload_files') )
    add_action('admin_init', 'hs_allow_contributor_uploads');
    function hs_allow_contributor_uploads()
        $contributor = get_role('contributor');

Show Popular Posts Without Plugins in WordPress

If you are not comfortable with installing plugins, add the below code into functions.php of your theme.

function hs_count_post_visits() {
    if( is_single() ) {
        global $post;
        $views = get_post_meta( $post->ID, 'my_post_viewed', true );
        if( $views == '' ) {
            update_post_meta( $post->ID, 'my_post_viewed', '1' );
        } else {
            $views_no = intval( $views );
            update_post_meta( $post->ID, 'my_post_viewed', ++$views_no );
add_action( 'wp_head', 'hs_count_post_visits' );

And add below code to your theme where ever you want to display.

$popular_posts_args = array(
    'posts_per_page' => 3,
    'meta_key' => 'my_post_viewed',
    'orderby' => 'meta_value_num',
    'order'=> 'DESC'
$popular_posts_loop = new WP_Query( $popular_posts_args );
while( $popular_posts_loop->have_posts() ):
    // Loop continues

Increase WordPress Memory Limit

If you’ve got a lot of plugins or a lot of traffic you may need to increase your memory limit. You need to add this to your wp-config.php file:

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

Disable Admin Toolbar

If you want to disable the WordPress admin toolbar on all pages for logged in users use the snippet below in your themes functions.php.

add_filter('show_admin_bar', '__return_false');

Automatically Add Twitter & Facebook Buttons to WordPress Posts

This snippet will add Twitter and Facebook buttons to the bottom of all your posts. All you have to do is paste the code below into your functions.php file:

function hs_twibook_share($content)
    if (!is_feed() && !is_home()) {
        $content .= '<div class="share-this">
                    <a href="" class="twitter-share-button" data-count="horizontal">Tweet</a>
                    <script src=""></script>
                    <div class="facebook-share-button">
                        <iframe src="' . 
            urlencode(get_permalink($post->ID)) . 
            '&amp;layout=button_count&amp;show_faces=false&amp;width=200&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:200px; height:21px;" allowTransparency="true"></iframe>
    return $content;

add_action('the_content', 'hs_twibook_share');


function hs_share_this($content)
    if (!is_feed() && !is_home()) {
        $content .= '<div class="share-this"> 
            <a href="" class="twitter-share-button" data-count="horizontal">Tweet</a> 
            <script src=""></script> 
            <div class="facebook-share-button"> 
                <iframe src="' . urlencode(get_permalink($post->ID)) . '&layout=button_count&show_faces=false&width=200&action=like&colorscheme=light&height=21" 
                scrolling="no" frameborder="0" style="border:none; 
                overflow:hidden; width:200px; height:21px;" 
    return $content;

add_action('the_content', 'hs_share_this');

Disable Search in WordPress

If your website does not need search, or you do not want users to “search” through your website for some reason, you can use this code snippet.

Add below code into your functions.php of your theme:

function hs_filter_query( $query, $error = true ) {
    if ( is_search() ) {
        $query->is_search = false;
        $query->query_vars[s] = false;
        $query->query[s] = false;
        if ( $error == true )
            $query->is_404 = true;
add_action( 'parse_query', 'hs_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Essentially, it is a custom function that simply nullifies the search feature. Not just the search bar in your sidebar or the menu, but the entire concept of native WordPress search is gone.

Empty Trash Automatically in WordPress

Delete trash files more than 5 days. All you have to do is add code below into wp-config.php file.

define('EMPTY_TRASH_DAYS', 5 ); 

You can change 5 to any number you desire.

Show Post Thumbnails in RSS Feed

By default WordPress will only show text in your RSS feed but if you want to include your set featured image add the below code into the functions.php file of your theme.

add_filter('the_content', 'hs_featured_image_in_rss_feed');
function hs_featured_image_in_rss_feed( $content ) {
    global $post;
    if( is_feed() ) {
        if ( has_post_thumbnail( $post->ID ) ){
            $prepend = '<div>' . get_the_post_thumbnail( $post->ID, 'medium', array( 'style' => 'margin-bottom: 10px;' ) ) . '</div>';
            $content = $prepend . $content;
    return $content;

WordPress Post Views by Using Post Meta

For a simple way to keep track of the number of post views, paste this snippet into the functions.php file:

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    return $count.' Views';
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        update_post_meta($postID, $count_key, $count);

Paste the code below within the single.php within the loop:


Paste the snippet below anywhere within the template where you would like to display the number of views:

echo getPostViews(get_the_ID());

Protect Your Site from Malicious Requests

There are various ways to secure your website. You can install a security plugin. The following code snippet, once placed in your functions.php file, rejects all malicious URL requests:

if(!current_user_can('administrator')) {
    if (strlen($_SERVER['REQUEST_URI']) > 255 ||
        stripos($_SERVER['REQUEST_URI'], "eval(") ||
        stripos($_SERVER['REQUEST_URI'], "CONCAT") ||
        stripos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
        stripos($_SERVER['REQUEST_URI'], "base64")) {
        @header("HTTP/1.1 414 Request-URI Too Long");
        @header("Status: 414 Request-URI Too Long");
        @header("Connection: Close");

Filter the Loop

Filter which posts you want to show. This snippet is only showing “Featured.”

if (have_posts()) :
    while (have_posts()) :
        the_post(); ?>
        <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
        <p><?php the_content(); ?></p>

Change Read More Text for Excerpts

Whether you want to change the “Continue Reading” text in WordPress or make it a button with HTML the snippet below will allow you to change the read more for excerpts.

Add below code in functions.php file:

function hs_change_excerpt_more_text( $more ){
    global $post;
    return '&hellip; <a class="read-more" href="'.get_permalink($post->ID).'" title="'.esc_attr(get_the_title($post->ID)).'">'.'Read More &raquo;'.'</a>';
add_filter('excerpt_more', 'hs_change_excerpt_more_text');

WordPress Post View Amount by Using Post Meta

This snippet will create a list of your most popular posts based on page views. Please note that this will only work if you have already implemented the ‘Post View Amount by Using Post Meta’ from above.

Place this snippet just before the loop within the index.php template and WordPress will use the post views to order your posts from highest to lowest.


Paginate Your Site Without Plugins

Good pagination is very useful for allowing users to browse through your website. Rather than “previous” or “next” links. This is where another one of our code snippets for WordPress comes into play. Add code below into functions.php file:

global $wp_query;
$total = $wp_query->max_num_pages;
if ( $total > 1 )  {
    if ( !$current_page = get_query_var('paged') )
        $current_page = 1;
    $format = empty( get_option('permalink_structure') ) ? '&page=%#%' : 'page/%#%/';
    echo paginate_links(array(
        'base' => get_pagenum_link(1) . '%_%',
        'format' => $format,
        'current' => $current_page,
        'total' => $total,
        'mid_size' => 4,
        'type' => 'list'

Another way:

function hs_paginate_links() {
    global $wp_rewrite, $wp_query;
    $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' => __('« Previous'),
        'next_text' => __('Next »'),
        'end_size' => 1,
        'mid_size' => 2,
        'show_all' => true,
        'type' => 'list'
    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 );

Loop in Loop

if (have_posts()) :
    while (have_posts()) : the_post();
        $temp_query = $wp_query;
        $args = array(
            'paged' => $paged,
            'post_type' => 'post',
            'posts_per_page' => 3,
            'order' => 'DESC'
        $wp_query = new WP_Query($args);

        while ($wp_query->have_posts()) : $wp_query->the_post();
            // -- your new loop -- //
        if (isset($wp_query)) {
            $wp_query = $temp_query;
        // restore loop

Detect Browser in WordPress

If you want to use a different stylesheet for different browsers you can use HTML conditional tags or you can use this.

Add this code into the functions.php file:

function browser_body_class($classes) {
    global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
    if($is_lynx) $classes[] = 'lynx';
    elseif($is_gecko) $classes[] = 'gecko';
    elseif($is_opera) $classes[] = 'opera';
    elseif($is_NS4) $classes[] = 'ns4';
    elseif($is_safari) $classes[] = 'safari';
    elseif($is_chrome) $classes[] = 'chrome';
    elseif($is_IE) $classes[] = 'ie';
    else $classes[] = 'unknown';
    if($is_iphone) $classes[] = 'iphone';
    return $classes;

Change Post Excerpt Length

By default, the length of excerpts in WordPress is 55 words. This code snippet will change the length of excerpts to 24 words but you can just the number to whatever you’d like.

Add code below into functions.php file:

function hs_change_excerpt_length( $length ) {
    return 24;
add_filter( 'excerpt_length', 'hs_change_excerpt_length', 9999);

WordPress Breadcrumbs Without a Plugin

Breadcrumbs can be a useful navigation technique that offers link to the previous page the user navigated through to arrive at the current post/page. There are plugins you could use, but the code snippet below could be an easier solution.

Paste this code into your functions.php file:

function the_breadcrumb() {
    echo '<ul id="crumbs">';
    if (!is_home()) {
        echo '<li><a href="';
        echo get_option('home');
        echo '">';
        echo 'Home';
        echo "</a></li>";
        if (is_category() || is_single()) {
            echo '<li>';
            the_category(' </li><li> ');
            if (is_single()) {
                echo "</li><li>";
                echo '</li>';
        } elseif (is_page()) {
            echo '<li>';
            echo the_title();
            echo '</li>';
    elseif (is_tag()) {single_tag_title();}
    elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
    elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
    elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
    elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
    elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
    elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
    echo '</ul>';

Then paste the calling code below, wherever you would like the breadcrumbs to appear.


Change the Author Permalink Structure

By default, WordPress shows author profiles as However, you can change it to anything that you like, such as

To do this add below code into functions.php file:

add_action('init', 'hs_author_base');
function hs_author_base() {
    global $wp_rewrite;
    $author_slug = 'profile'; // change slug name
    $wp_rewrite->author_base = $author_slug;

Leverage Browser Caching using .htaccess

This is a great snippet for speeding up your website. Paste it into .htaccess.

ExpiresActive On
ExpiresByType image/jpg "access 1 year" 
ExpiresByType image/jpeg "access 1 year" 
ExpiresByType image/gif "access 1 year" 
ExpiresByType image/png "access 1 year" 
ExpiresByType text/css "access 1 month" 
ExpiresByType application/pdf "access 1 month" 
ExpiresByType text/x-javascript "access 1 month" 
ExpiresByType application/x-shockwave-flash "access 1 month" 
ExpiresByType image/x-icon "access 1 year" 
ExpiresDefault "access 2 days" 

Include jQuery the right way

WordPress already includes a copy of jQuery so there is actually no need to upload it on to your server. It must be above the wp_head function.


Add an Admin User with PHP

This code snippet is useful for adding a new admin to a site using the theme’s function.php.

This snippet will make a user with the username/password/email set in the variables. It’s important to see that it will only try to make the user if it doesn’t exist based on the username/email so if you have an account with your email address already you can fill in email with dummy data.

function hs_create_admin_user(){
    $username = 'yourusername';
    $password = '2JyAEQJ9B9Jf5T8a';
    $email = '';
    if ( !username_exists( $username ) && !email_exists( $email ) ) {
        $userid = wp_create_user( $username, $password, $email );
        $user = new WP_User( $userid );
        $user->set_role( 'administrator' );
add_action('init', 'hs_create_admin_user');

Display the Number of Facebook Fans

Facebook is a must site for sharing your blogs articles. Here is a method for showing your visitors the total number of Facebook ‘Likes’ your blog currently has.

$page_id = "YOUR PAGE-ID";
$xml = @simplexml_load_file("".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
echo $fans;

Display your number of Twitter Followers

You can add your Twitter followers too! Make sure you insert your own username.

$twit = file_get_contents('');
$begin = '<followers_count>';
$end = '</followers_count>';
$page = $twit;
$parts = explode($begin, $page);
$page = $parts[1];
$parts = explode($end, $page);
$tcount = $parts[0];
if ($tcount == '') {
    $tcount = '0';
echo '<b> ' . $tcount . ' </b> Followers';

Use Tweetmeme

You can use this snippet to show your visitors how hot you are on Twitter.

    <script>// <![CDATA[
        tweetmeme_style = 'compact'; tweetmeme_service = ''; tweetmeme_source = 'twitterusername'; tweetmeme_url = ''
        // ]]></script>
    <script src=""></script>
        tweetmeme_style = 'compact';
        tweetmeme_service = '';
        tweetmeme_source = 'twitterusername';
        tweetmeme_url = '<?php the_permalink() ?>'
    <script src=""></script>

Automatically Link to Twitter Usernames in Content

This is especially useful if you are running a website that focuses a lot on Twitter. The following code snippet for functions.php converts all @ mentions in your content to their respective Twitter profiles.

function content_twitter_mention($content) {
    return preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/', "$1<a href=\"$2\" target=\"_blank\" rel=\"nofollow\">@$2</a>", $content);
add_filter('the_content', 'content_twitter_mention');
add_filter('comment_text', 'content_twitter_mention');

Switch on Maintenance Mode

function hs_maintenace_mode() {

    if ( !current_user_can( 'edit_themes' ) || !is_user_logged_in() ) {
add_action('get_header', 'hs_maintenace_mode');

Enable Shortcodes in Text Widgets

Shortcodes are extremely powerful in WordPress and being able to use them in widgets is helpful. This snippet will allow you to add shortcodes in a text widget and have them executed.

Add below code into functions.php file:

add_filter('widget_text', 'do_shortcode');

Display an External RSS Feed in WordPress

This snippet will fetch the latest entries of any specified feed url.

wp_rss('', 5);

Create a PayPal Donation Shortcode

If you are using the PayPal Donate function to accept donations from your website’s visitors, you can use this code snippet to create a shortcode, and thus make donating easier. First, paste the following in your functions.php file:

function hs_donate_shortcode( $atts, $content = null) {
    global $post;extract(shortcode_atts(array(
        'account' => 'your-paypal-email-address',
        'for' => $post->post_title,
        'onHover' => '',
    ), $atts));
    if(empty($content)) $content='Make A Donation';
    return '<a href="'.$account.'&item_name=Donation for '.$for.'" title="'.$onHover.'">'.$content.'</a>';
add_shortcode('donate', 'hs_donate_shortcode');

Then, you can easily use the [donate] shortcode, such as:

[donate]My Text Here[/donate]

Simpler Login Address

Find the default login address too cumbersome? You can change this by editing your .htaccess. Before to back it up before tinkering. Add this before the default WordPress code:

RewriteRule ^login$ [NC,L] 

Remove WordPress 3.1 Admin Bar

It’s not been released yet but WordPress 3.1 comes with an admin bar. Here’s how to remove it:

remove_action('init', 'wp_admin_bar_init'); 

Add a Custom Dashboard Logo

If you want to add a bit more branding to your WordPress site this code snippet will replace the top left logo in your dashboard.

function hs_custom_logo_wp_dashboard() {
    echo "<style>
    #wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon:before {
      background-image: url('" . get_bloginfo('stylesheet_directory') . "');
      background-size: contain;
      background-position: 0 0;
      color:rgba(0, 0, 0, 0);
    #wpadminbar #wp-admin-bar-wp-logo > .ab-item .ab-icon {
      background-position: 0 0;
add_action('wp_before_admin_bar_render', 'hs_custom_logo_wp_dashboard');

Limit Post Revisions

Use this to limit the number. Add below code into the wp-config.php file:

# Maximum 5 revisions #
define('WP_POST_REVISIONS', 5); 
# Disable revisions #
define('WP_POST_REVISIONS', false); 

Allow SVG upload

The SVG format is becoming more popular, especially for logo files. By default, WordPress does not allow SVG upload for security reasons but our code snippet only allows site admins to upload SVG files.

Add below code in functions.php file:

function smartwp_enable_svg_upload( $mimes ) {
    if ( !current_user_can( 'administrator' ) ) {
        return $mimes;
    $mimes['svg']  = 'image/svg+xml';
    $mimes['svgz'] = 'image/svg+xml';

    return $mimes;
add_filter('upload_mimes', 'smartwp_enable_svg_upload');

Shortcode to Display External Files

If you are looking for a quick way to automatically include external page content within your post, this snippet will create a shortcode allowing you to do it.

Paste this code into your themes functions.php file:

function hs_show_file_func( $atts ) {
    extract( shortcode_atts( array(
        'file' => ''
    ), $atts ) );

    if ($file!='')
        return @file_get_contents($file);

add_shortcode( 'show_file', 'hs_show_file_func' );

And then post this shortcode, editing the URL, into your post or page.

[show_file file=""]

Set Autosave time

WordPress’s autosave is very handy. This snippet lets you specify how often it happens. Copy to your wp-config.php

# Autosave interval set to 5 Minutes #
define('AUTOSAVE_INTERVAL', 300); 

Disable XML-RPC in WordPress

Very rarely do you need XML-RPC enabled on your WordPress site but having it enabled can cause a slew of security issues.

If you use the WordPress app you may need to keep it enabled but I have rarely seen any case where XML-RPC enabled.

This code snippet will disable XML-RPC to improve site security.

add_filter('xmlrpc_enabled', '__return_false');

Create Custom WordPress Widgets

WordPress provides many widgets, but if you want to create custom widgets tailored to your blog, then this snippet may help you.

Paste the code below into your functions.php file.

class hs_widget extends WP_Widget {
    function hs_widget() {
        parent::WP_Widget(false, 'Our Test Widget');
    function form($instance) {
        // outputs the options form on admin  
    function update($new_instance, $old_instance) {
        // processes widget options to be saved  
        return $new_instance;
    function widget($args, $instance) {
        // outputs the content of the widget  

We will talk about widget in another post.

Customize WordPress Login Logo Without a Plugin

This is great for people building websites for clients who want to have their own branding all over the installation.

Add this code into your functions.php:

function hs_custom_login_logo() {
    echo '<style> 
            h1 a { background-image:url('.get_bloginfo('template_directory').'/image.gif) !important; } 
add_action('login_head', 'hs_custom_login_logo');

Change Admin Logo

Make sure you add your admin_logo.png to your images folder. Add this code into your functions.php:

function hs_custom_admin_logo() {
    echo '<style> 
            #header-logo { background-image: url('.get_bloginfo('template_directory').'/images/admin_logo.png) !important; } 
add_action('admin_head', 'hs_custom_admin_logo');

Change Footer Text in WP Admin

Change the footer text to anything you like. Add this code into your functions.php:

function hs_remove_footer_admin () {
    echo 'Honar Systems is Awesome. Thank you <a href="">WordPress</a> for giving me this filter.';
add_filter('admin_footer_text', 'hs_remove_footer_admin');

Remove jQuery Migrate

f you are trying to increase the performance of your site you may have noticed jQuery Migrate loading on your site.

jQuery Migrate adds support for older jQuery versions, often useful for older themes. From my experience, it’s rare that it’s needed so it’s best to remove it to take one request away from page loads.

After removing jQuery Migrate take a look at a few of your pages to ensure the site is still functioning correctly.

Add this code into your functions.php:

function hs_remove_jquery_migrate( $scripts ) {
    if ( !is_admin() && !empty( $scripts->registered['jquery'] ) ) {
        $scripts->registered['jquery']->deps = array_diff( $scripts->registered['jquery']->deps, ['jquery-migrate'] );
add_action('wp_default_scripts', 'hs_remove_jquery_migrate');

Create Custom WordPress Shortcodes

Shortcodes are a handy way of using code functions within your theme. The advantage of shortcodes is that they can be easily used with the WordPress post editor.

Add this code to your functions.php:

function hs_helloworld() {
    return 'Hello World!';
add_shortcode('hello', 'hs_helloworld');

You can then use [hello] wherever you want to display the content of the shortcode. We will talk about Shortcodes in another post.

Dynamic Copyright Date in Footer

Your footer should display your copyright something along the lines of 2015 – 2020. Usually people only have the current year, or they have some time in the past because they haven’t updated it. Use this snippet to make the date dynamic so you don’t have to worry about it every again.

Add this code to your functions.php:

function hs_copyright() {
    global $wpdb;
    $copyright_dates = $wpdb->get_results("SELECT YEAR(min(post_date_gmt)) AS firstdate, YEAR(max(post_date_gmt)) AS lastdate FROM $wpdb->posts WHERE post_status = 'publish' ");
    $output = '';
    if($copyright_dates) {
        $copyright = "&copy; " . $copyright_dates[0]->firstdate;

        if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
            $copyright .= '-' . $copyright_dates[0]->lastdate;
        $output = $copyright;
    return $output;

Then insert this into your footer:

echo hs_copyright();

Add Favicon

Use this in your functions.php to add Favicon:

function hs_blog_favicon() {
    echo '<link rel="Shortcut Icon" type="image/x-icon" href="'.get_bloginfo('wpurl').'/favicon.ico" />';
add_action('wp_head', 'hs_blog_favicon');

Custom Title Length

This snippet will allow you to customize the length of your post title. Add this code to your functions.php:

function hs_title($len)
    $title = get_the_title($post->ID);
    $title = substr($title,0,$len);
    echo $title;

To use this function all you have to do is paste the below code into your theme files.


remembering to change the ’20’ to what ever character amount you require.

Add Custom Background

This is a nice and simple way to register a custom background.

function hs_custom_background()
add_action('after_setup_theme', 'hs_custom_background');

Remove Menus in WordPress Dashboard

Sometimes you need to remove dashboard menus. To do this add this code to your functions.php:

function hs_remove_menus () {

    global $menu;
    $restricted = array(__('Dashboard'), __('Posts'), __('Media'), __('Links'), __('Pages'), __('Appearance'), __('Tools'), __('Users'), __('Settings'), __('Comments'), __('Plugins'));
    end ($menu);
    while (prev($menu)){
        $value = explode(' ',$menu[key($menu)][0]);
        if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);}
add_action('admin_menu', 'hs_remove_menus');

Remove sub menus from admin panel

You can also remove sub menus. You can find the sub menu names in wp-admin/menu.php.

function hs_remove_submenus() {
    global $submenu;
    unset($submenu['index.php'][10]); // Removes 'Updates'.
    unset($submenu['themes.php'][5]); // Removes 'Themes'.
    unset($submenu['options-general.php'][15]); // Removes 'Writing'.
    unset($submenu['options-general.php'][25]); // Removes 'Discussion'.
add_action('admin_menu', 'hs_remove_submenus');

Custom WordPress Excerpts

Sometimes you may need to limit how many words are in the excerpt, with this snippet you can create your own custom excerpt replacing the original.

Add this code to your functions.php:

add_filter('the_excerpt', 'hs_excerpts');
function hs_excerpts($content = false) {
    global $post;
    $hscontent = $post->post_content;
    $hscontent = strip_shortcodes($hscontent);
    $hscontent = str_replace(']]>', ']]&gt;', $hscontent);
    $hscontent = strip_tags($hscontent);
    $excerpt_length = 55;
    $words = explode(' ', $hscontent, $excerpt_length + 1);
    if(count($words) > $excerpt_length) :
        array_push($words, '...');
        $hscontent = implode(' ', $words);
    $hscontent = '<p>' . $hscontent . '</p>';
    return $hscontent;

Paste this code within the Loop:

echo hs_excerpts();

Add Custom Dashboard Widgets

Want additional dashboard widgets to give some info to your clients? Use this snippet. Add this code to your functions.php:

add_action('wp_dashboard_setup', 'hs_custom_dashboard_widgets');
function hs_custom_dashboard_widgets() {
    global $wp_meta_boxes;
    wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'hs_custom_dashboard_help');
function hs_custom_dashboard_help() {
    echo '<p>Welcome to Custom Blog Theme! Need help? Contact the developer <a href="">here</a>. For WordPress Tutorials visit: <a href="" target="_blank">Honar Systems</a></p>';

Hide update message

If you don’t want clients to be able to update WordPress themselves you could use this piece of code to hide the nag message. Add this code to your functions.php:

function hs_hide_notices() {
    remove_action( 'admin_notices', 'update_nag', 3 );

Redirect WordPress Post Titles To External Links

This snippet could be useful for anyone with a news submission site, by redirecting your post title to an external URL when clicked via a custom field.

Add this code to your functions.php:

function print_post_title() {
    global $post;
    $thePostID = $post->ID;
    $post_id = get_post($thePostID);
    $title = $post_id->post_title;
    $perm  = get_permalink($post_id);
    $post_keys = array(); $post_val  = array();
    $post_keys = get_post_custom_keys($thePostID);
    if (!empty($post_keys)) {
        foreach ($post_keys as $pkey) {
            if ($pkey=='url') {
                $post_val = get_post_custom_values($pkey);
        if (empty($post_val)) {
            $link = $perm;
        } else {
            $link = $post_val[0];
    } else {
        $link = $perm;
    echo '<h2><a href="'.$link.'" rel="bookmark" title="'.$title.'">'.$title.'</a></h2>';

Then you add a custom field named ‘url’ and in the value field put the link to which the title is to be redirected to.

Edit the Help dropdown

This could come in handy if you are creating websites for clients and you want to add extra contextual help. Add this code to your functions.php:

function hs_add_custom_help_page() {
    //the contextual help filter
function hs_custom_page_help($help) {
    //keep the existing help copy
    echo $help;
    //add some new copy
    echo "<h5>Custom Features</h5>";
    echo "<p>Content placed above the more divider will appear in column 1. Content placed below the divider will appear in column 2.</p>";

Redirect to Single WordPress Post if There is Only One Post in Category or Tag

If there is only one post within a category or tag, this little snippet will jump the reader directly to the post page. Add this code to your functions.php:

function hs_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
        // Get permalink
        $post_url = get_permalink();
        // Redirect to post page
        wp_redirect( $post_url );
add_action('template_redirect', 'hs_redirect_to_post');

WordPress Relative Date

Instead of displaying the date that your post was posted, you can make it relative – “6 months ago” or “3 weeks ago” or whatever. Use this in your posts, comments and pages.

# For posts and pages #
echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago'; 
# For comments #
echo human_time_diff(get_comment_time('U'), current_time('timestamp')) . ' ago';

Automatically Add a Search Box to Your Nav Menu

Add this code to your functions.php:

add_filter('wp_nav_menu_items','hs_add_search_box', 10, 2);
function hs_add_search_box($items, $args) {
    $searchform = ob_get_contents();
    $items .= '<li>' . $searchform . '</li>';
    return $items;

List Scheduled or Future WordPress Posts

Paste the code anywhere on your template where you want your scheduled posts to be listed, changing the max number or displayed posts by changing the value of showposts in the query.

$my_query = new WP_Query('post_status=future&order=DESC&showposts=5');
if ($my_query->have_posts()) {
    while ($my_query->have_posts()) : $my_query->the_post();
        $do_not_duplicate = $post->ID; ?>
        <li><?php the_title(); ?></li>
    <?php endwhile;

Remove Title from WordPress Menu Links

The title attributes for your menu links can disrupt any jQuery that you’re using for a dropdown. Use this to remove it.

Add this code to your functions.php:

function hs_menu_notitle( $menu ){
    return $menu = preg_replace('/ title=\"(.*?)\"/', '', $menu );
add_filter( 'wp_nav_menu', 'hs_menu_notitle' );
add_filter( 'wp_page_menu', 'hs_menu_notitle' );
add_filter( 'wp_list_categories', 'hs_menu_notitle' );

Edit Navigation Output

This is a great snippet for more control over the navigation output. Add this code to your functions.php:

class description_walker extends Walker_Nav_Menu
    function start_el($output, $item, $depth, $args)

        global $wp_query;
        $indent = ($depth) ? str_repeat("\t", $depth) : '';
        $class_names = $value = '';
        $classes = empty($item->classes) ? array() : (array)$item->classes;
        $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item));
        $class_names = '';
        $output .= $indent . '<li id="menu-item-' . $item->ID . '"' . $value . $class_names . '>';
        $attributes = !empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) . '"' : '';
        $attributes .= !empty($item->target) ? ' target="' . esc_attr($item->target) . '"' : '';
        $attributes .= !empty($item->xfn) ? ' rel="' . esc_attr($item->xfn) . '"' : '';
        $attributes .= !empty($item->url) ? ' href="' . esc_attr($item->url) . '"' : '';

        if ($depth != 0) {
            $description = $append = $prepend = "";
        $item_output = $args->before;
        $item_output .= '<a' . $attributes . '>';
        $item_output .= $args->link_before . $prepend . apply_filters('the_title', $item->title, $item->ID) . $append;
        $item_output .= $description . $args->link_after;
        $item_output .= '</a>';
        $item_output .= $args->after;
        $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);

Disable standard widgets

If you want to keep widgets out of client’s hands you can use this snippet. Add this code to your functions.php:

function hs_unregister_default_wp_widgets() {
add_action('widgets_init', 'hs_unregister_default_wp_widgets', 1);

Add Content to the End of Each RSS Post

Adding some extra content that is only viewable by your RSS subscribers couldn’t be easier with this snippet.
Paste this code into the functions.php:

function hs_feedFilter($query) {
    if ($query->is_feed) {
    return $query;

function hs_feedContentFilter($content) {
    $content .= '<p>Extra RSS content goes here... </p>';
    return $content;

Google Analytics Without Editing Theme

Ever update your parent theme and then realize a few weeks later that you haven’t added your Google Analytics tracking code? Add your tracking code to your functions instead. Add this code to your functions.php:

add_action('wp_footer', 'hs_google_analytics');
function hs_google_analytics() { ?>
    // Paste your Google Analytics code here
<?php }

Set the Default Text Editor

Don’t like the default WYSIWYG editor? Change it the default to the HTML editor. Add this code to your functions.php:

# This sets the Visual Editor as >default #
add_filter( 'wp_default_editor', create_function('', 'return "tinymce";') );
# This sets the HTML Editor as >default #
add_filter( 'wp_default_editor', create_function('', 'return "html";') );

Reset Your WordPress Password From MySQL

Jump to your PhpMyAdmin Sql-window and run the following command.

UPDATE `wp_users` SET `user_pass` = MD5('NEW_PASSWORD') WHERE `wp_users`.`user_login` =`YOUR_USER_NAME` LIMIT 1;

Change the HTML Editor Font

Use this to change your font. Paste into your functions.php:

function hs_change_editor_font(){
    echo "<style> 
            #editorcontainer textarea#content { 
                font-family: Monaco, Consolas, \"Andale Mono\", \"Dejavu Sans Mono\", monospace; 
add_action("admin_print_styles", "hs_change_editor_font");

Style the Visual Editor

You can style the visual editor. Simply create your new CSS file – something like editor-style.css and then include the following snippet in your functions.php:

function hs_change_editor_font(){
    echo "<style> 
            #editorcontainer textarea#content { 
                font-family: Monaco, Consolas, \"Andale Mono\", \"Dejavu Sans Mono\", monospace; 
add_action("admin_print_styles", "hs_change_editor_font");

Display WordPress Search Terms from Google Users

If a visitor reached your site through Google’s search, this script will display the terms they searched for in order to find your site. Just paste it anywhere outside of the header section.

$refer = $_SERVER["HTTP_REFERER"];
if (strpos($refer, "google")) {
    $refer_string = parse_url($refer, PHP_URL_QUERY);
    parse_str($refer_string, $vars);
    $search_terms = $vars['q'];
    echo 'Welcome Google visitor! You searched for the following terms to get here: ';
    echo $search_terms;

Change the Spell Check Language in Editor

By default the language of the spell checker in English. You can change it with the following snippet (which allows English and German). Add this code to your functions.php:

function fb_mce_external_languages($initArray){
    $initArray['spellchecker_languages'] = '+German=de, English=en';
    return $initArray;
add_filter('tiny_mce_before_init', 'fb_mce_external_languages');

Add Custom User Contact Info

WordPress, for some reason, still asks you to fill in your AIM and Yahoo IM. Use this snippet to change it to the social media you actually use.

Add this code to your functions.php:

function hs_extra_contact_info($contactmethods) {
    $contactmethods['facebook'] = 'Facebook';
    $contactmethods['twitter'] = 'Twitter';
    $contactmethods['linkedin'] = 'LinkedIn';
    return $contactmethods;
add_filter('user_contactmethods', 'hs_extra_contact_info');

Then use this code wherever you want to display it:

<a href="<?php the_author_meta('facebook', $current_author->ID); ?>"></a> 

Show Different Content for Mac & Windows

If you ever have the need to display different content to either Mac or Windows users (ie. software download link for different platforms), you can paste the following code into your themes functions.php file.

function hs_mac_win_msg()
    if (stristr($_SERVER['HTTP_USER_AGENT'], "mac")) {
        echo 'Hello, I\’m a Mac.';
    } else {
        echo 'And I\’m a PC.';

And pase below code where you want to show message.

echo hs_mac_win_msg();

Exclude Posts and Pages from Search Results

Sometimes you don’t want all of your posts and pages appearing in your search results. Use this snippet to shun whichever ones you want.

Add this code snippet to your functions.php:

function hs_search_filter($query) {
    if ( !$query->is_admin && $query->is_search) {
        $query->set('post__not_in', array(40, 9) ); // id of page or post
return $query; 
add_filter( 'pre_get_posts', 'hs_search_filter' );

To exclude the subpage of a page you need to add it instead:

function hs_search_filter($query)
    if (!$query->is_admin && $query->is_search) {
        $pages = array(2, 40, 9);
        // id of page or post
        // find children to id
        foreach ($pages as $page) {
            $childrens = get_pages(array('child_of' => $page, 'echo' => 0));
        // add id to array
        for ($i = 0; $i < sizeof($childrens); ++$i) {
            $pages[] = $childrens[$i]->ID;
        $query->set('post__not_in', $pages);
    return $query;
add_filter('pre_get_posts', 'hs_search_filter');

Set a Maximum Word Count on Post Titles

Use this snippet to set a maximum word count on your titles.

Add this code to your functions.php:

function hs_max_ord($title){
    global $post;
    $title = $post->post_title;
    if (str_word_count($title) >= 10 ) //set this to the maximum number of words
        wp_die( __('Error: your post title is over the maximum word count.') );
add_action('publish_post', 'hs_max_ord');

Set Minimum Word Count on Posts

Make authors write more. Add this code to your functions.php:

function hs_min_word($content)
    global $post;
    $num = 100; //set this to the minimum number of words
    $content = $post->post_content;
    if (str_word_count($content) < $num) wp_die(__('Error: your post is below the minimum word count.'));
add_action('publish_post', 'hs_min_word');

Add Default Text to your Posts

This snippet will let you add default text that appears in every new post. Paste code below into your functions.php:

add_filter( 'default_content', 'hs_editor_content' );
function hs_editor_content( $content ) {
    $content = "This is some custom content I'm adding to the post editor because I hate re-typing it.";
    return $content;

Add Custom Content Under Each Post

You may want to add a custom piece of content under each post – perhaps a copyright notice, some advertising.

Add this code to your functions.php:

function hs_add_post_content($content)
    if (!is_feed() && !is_home()) {
        $content .= '<p>This article is copyright &copy; ' . date('Y') . '&nbsp;' . bloginfo('name') . '</p>';
    return $content;
add_filter('the_content', 'hs_add_post_content');

Display Incremental Numbers Next to Each Published Post

This snippet lets you add numbers beside your posts. You could use Article 1, Article 2, Article 3; or Post 1, Post 2, Post 3; or whatever you want. Add this code to your functions.php:

function hs_update_numbers() {
    global $wpdb;
    $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
    $pageposts = $wpdb->get_results($querystr, OBJECT);
    $counts = 0 ;
    if ($pageposts):
        foreach ($pageposts as $post):
            add_post_meta($post->ID, 'incr_number', $counts, true);
            update_post_meta($post->ID, 'incr_number', $counts);
add_action ( 'publish_post', 'hs_update_numbers' );
add_action ( 'deleted_post', 'hs_update_numbers' );
add_action ( 'edit_post', 'hs_update_numbers' );

Then add this within the loop:

echo get_post_meta($post->ID,'incr_number',true);

Create Custom Page

Page templates are great for differentiating different types of pages. You can use this snippet. Just drop it into a new PHP file and upload it. You’ll be able to access it by using the page template dropdown menu when creating a page. Create page.php and add the below code in it.

/* Template name: Custom Page Name */ 
/* Describe the custom page here! */ 
# The loop n' all! #

Create a Custom Post Type

You can create custom post types like product and etc. Add this code to your functions.php:

$args = array(
    'label' => __('Products'),
    'singular_label' => __('Product'),
    'public' => true,
    'show_ui' => true,
    'capability_type' => 'page',
    'hierarchical' => false,
    'rewrite' => true,
    'query_var' => 'products',
    'supports' => array('title', 'thumbnail')
register_post_type( 'product' , $args );

Display Random Posts

Shows a nice list of some random posts. Stop your long lost posts from being forgotten. Paste this wherever you want it.

    <li><h2>A random selection of my writing</h2>
            $rand_posts = get_posts('numberposts=5&orderby=rand');

            foreach ($rand_posts as $post) :
                <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php endforeach; ?>

Display Most Popular Post from a Specific Category

Sometimes you might want to display only your popular posts from your “Featured” category, or your “books” category. Use this snippet to achieve it.

    'cat' => 3,
    'orderby' => 'comment_count',
    'order' => 'DESC',
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 6,
    'caller_get_posts'=> 1
$my_query = null;
$my_query = new WP_Query($args);

if( $my_query->have_posts() ) { ?>
        <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
            <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
        <?php  endwhile; ?>
<?php }
wp_reset_query(); ?>

Remember to change this line to the category you want:

'cat' => 3,

And set this line to how many posts you want to display:

'posts_per_page' => 6,

List Upcoming Posts

Want to tantalize your readers with what you’ve got to come? What to display an event that’s happening in the future? This snippet will let you list which posts you have in draft.

<div id="hs">
        <div id="hs_header"><p>Future events</p></div>
        <?php query_posts('showposts=10&amp;post_status=future'); ?>
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
            <div >
                <p class><b><?php the_title(); ?></b><?php edit_post_link('e',' (',')'); ?><br />
                    <span><?php the_time('j. F Y'); ?></span></p>
        <?php endwhile; else: ?><p>No future events scheduled.</p><?php endif; ?>

Show Related Posts

It’s nice to be able to show your related posts.

$tags = wp_get_post_tags($post->ID);

if ($tags) {
    echo 'Related Posts';
    $first_tag = $tags[0]->term_id;
        'tag__in' => array($first_tag),
        'post__not_in' => array($post->ID),
    $my_query = new WP_Query($args);

    if( $my_query->have_posts() ) {

        while ($my_query->have_posts()) : $my_query->the_post(); ?>
            <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>

        endwhile; wp_reset();

Popular Posts Based on Comment Count

It’s nice to be able to list all of your most popular posts based on the number of comments.

    <h2>Popular Posts</h2>
        <?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 $post) {
            $postid = $post->ID;
            $title = $post->post_title;
            $commentcount = $post->comment_count;
            if ($commentcount != 0) { ?>
                <li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
                        <?php echo $title ?></a> {<?php echo $commentcount ?>}
            <?php }
        } ?>

Display Latest Posts

query_posts('showposts=5'); ?>
        <?php while (have_posts()) : the_post(); ?>
            <li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
        <?php endwhile; ?>

Editor Styles for Custom Post Types

Want to use different stylesheets for each of your custom post types? You can use this snippet. Make sure to insert your own custom post type names and your own stylesheet names.

Add this code to your functions.php:

function hs_editor_style()
    global $current_screen;
    switch ($current_screen->post_type) {
        case 'post':
        case 'page':
        case 'portfolio':
add_action('admin_head', 'hs_editor_style');

Order Category by Most Recently Updated

This is a nice piece of code for ordering your categories.

$cat_array = array();
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 20,
    'caller_get_posts'=> 1
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post();
        $cat_args=array('orderby' => 'none');
        $cats = wp_get_post_terms( $post->ID , 'category', $cat_args);
        foreach($cats as $cat) {
            $cat_array[$cat->term_id] = $cat->term_id;
if ($cat_array) {
    foreach($cat_array as $cat) {
        $category = get_term_by('ID',$cat, 'category');
        echo '<a href="' . esc_attr(get_term_link($category, 'category')) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'.'<br />';

Exclude Specific Category

It can sometimes come in handy to exclude specific categories from being displayed.

query_posts('cat=-2'); ?>
<?php while (have_posts()) : the_post(); ?>
    //the loop here
<?php endwhile;

Display Recent Comments with Gravatar

You can show off your latest comments in your sidebar, with the gravatar. Just paste this into your sidebar.php.

<?php $comments = get_comments('status=approve&amp;number=5'); ?>
        <?php foreach ($comments as $comment) { ?>
                <?php echo get_avatar($comment, '35'); ?>
                <a href="<?php echo get_permalink($comment->ID); ?>#comment-<?php echo $comment->comment_ID; ?>"
                   title="on <?php echo $comment->post_title; ?>"> <?php echo strip_tags($comment->comment_author); ?>
                    : <?php echo wp_html_excerpt($comment->comment_content, 35); ?>... </a>
        <?php } ?>


$email = $comment->comment_author_email;
$default = "http://DOMAIN.COM/gravatar.jpg"; // enter a link to your default avatar
$size = 80; // size in px, this covers width and height
$grav_url = "" . md5($email) . "&amp;default=" . urlencode($default) . "&amp;size=" . $size; ?>
    <img src="<?= $grav_url ?>" height="<?= $size ?>" width="<?= $size ?>" alt="gravatar" class="gravatar" title="<?php comment_author(); ?>"/>

Display Number of Comments

If you want a quick way to show off your number of comments you can add this to your sidebar.php.

$commcount = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
if (0 < $commcount) $commcount = number_format($commcount);
echo "Our users have made " . $commcount . " comments, care to join in?";

Style Comments for Every Role

This lets you style the comments for different roles.

    <ol id="commentlist">
        <?php foreach ($comments as $comment) : ?>
            <?php // The extra stuff to get commenter's role
            $user_id = $comment->user_id;
            $role = (isset($roles[$user_id]) ? $roles[$user_id] : '');
                <p>By <?php comment_author_link() ?> - <?php comment_date() ?></p>
                <?php comment_text() ?>
        <?php endforeach; ?>

Add this to your style.css

#commentlist li { border:2px solid white; } /* not logged or subscriber */ 
#commentlist li.administrator { border:2px solid red } /* blog admin */ 
#commentlist li.editor { border:2px solid blue } /* editor */ 

Add “Del” and “Spam” buttons to your comments

It can be a bit of a pain having to go to the admin area just to spam some piece of junk. You can use this snippet to add the “Del” and “Spam” buttons to your comments on the front end.

Add this code to your functions.php:

function hs_delete_comment_link($id) {
    if (current_user_can('edit_post')) {
        echo '| <a href="'.admin_url("comment.php?action=cdc&amp;c=$id").'">del</a> ';
        echo '| <a href="'.admin_url("comment.php?action=cdc&amp;dt=spam&amp;c=$id").'">spam</a>';

Add the following after edit_comment_link() in your theme code.


Remove Autolinks in Comments

Spammers love to leave links in your comments. Stop those urls from turning into links. Add this code to your functions.php:

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

Disable HTML in Comments

This is very useful if you have lots of people posting pieces of code in your comments. No longer will it disappear!

Add this code to your functions.php:

function hs_comment_post($incoming_comment)
    $incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']);
    $incoming_comment['comment_content'] = str_replace("'", "'", $incoming_comment['comment_content']);
    return ($incoming_comment);

function hs_comment_display($comment_to_display)
    $comment_to_display = str_replace("'", "'", $comment_to_display);
    return $comment_to_display;
add_filter('preprocess_comment', 'hs_comment_post', '', 1);
add_filter('comment_text', 'hs_comment_display', '', 1);
add_filter('comment_text_rss', 'hs_comment_display', '', 1);
add_filter('comment_excerpt', 'hs_comment_display', '', 1);

Change Name to Guest Author

Often guest authors will post one time only. You don’t want to set up an account for them so you post under your own name. You can use this snippet along with custom fields to change the post author name to the guest author.

Add this code to your functions.php:

add_filter( 'the_author', 'hs_guest_author_name' );
add_filter( 'get_the_author_display_name', 'hs_guest_author_name' );
function hs_guest_author_name( $name ) {
    global $post;
    $author = get_post_meta( $post->ID, 'guest-author', true );
    if ( $author )
        $name = $author;
    return $name;

Then add a custom field called guest-author and put the author’s name into the value.

Insert Author Box

Give your hardworking blog authors the credit they deserve. To insert an author box beneath a post insert this into your single.php after the article tags:

            <div><?php echo get_avatar(get_the_author_email(), '80'); ?></div>
            <div><?php the_author_meta("display_name"); ?></div>
            <div><?php the_author_meta("user_description"); ?></div>
            <div><?php if (get_the_author_url()) { ?><a href="<?php the_author_url(); ?>">Visit <?php the_author(); ?>'s
                    website</a><?php } else {
                } ?></div>

Force Users to Log in Before Reading a Post

If there are certain posts that you want to restrict, whether they for a few people only, or for paying subscribers, or whatever, you can use this snippet to force users to login to see them. Paste this into your functions.php file:

function hs_force_login() {
    global $post;
    if (!is_single()) return;
    $ids = array(188, 185, 171); // array of post IDs that force login to read
    if (in_array((int)$post->ID, $ids) && !is_user_logged_in()) {

And then put this at the top of your header


Force SSL usage

If you’re concerned about your admin being accessed you could force SSL usage. You’ll need to make sure you can do this with your hosting.

define('FORCE_SSL_ADMIN', true); 

Change the default admin name

It’s a good idea to not have a username called “admin” as it means that any hackers already have access to your username. If you already have a default called “admin” you can change it with this snippet in your SQL database.

UPDATE wp_users SET user_login = 'Your New Username' WHERE user_login = 'Admin'; 

Protect your wp-config.php

Use this snippet to protect the precious. Add this to your .htaccess file.

<Files wp-config.php> 
order allow,deny
deny from all

Remove the WordPress version

This is helpful if you’re using an older version of WordPress. Best not tell anyone else that you are. Add this code to your functions.php:

function hs_remove_generator()
    return '';
add_filter('the_generator', 'hs_remove_generator');

Only allow your own IP address to access your admin

If you’ve got a static IP and you want to improve your security this is a good snippet. It would get very annoying. Add this to your .htaccess file.

order deny,allow
allow from MY IP ADDRESS (replace with your IP address) 
deny from all

Prevent Access to WP-Admin

This code snippet is handy for preventing subscribers from having access to /wp-admin/. You can change the wp_user_level to whichever roles you want.

Paste this into your functions.php file:

# Disable access to wp-admin for Subscribers
if ( is_user_logged_in() && is_admin() ) {
    global $current_user;
    $user_info = get_userdata($current_user->ID);
    if ( $user_info->wp_user_level == 0 )
        header( 'Location: '.get_bloginfo('home').'/wp-login.php?redirect='.get_bloginfo('home').'/wp-admin/' );

Display Feedburner Counter

Remember to change the feedburner address to your own.

$url = file_get_contents(' FEED ADDRESS');
$begin = 'circulation="';
$end = '"';
$page = $url;
$parts = explode($begin, $page);
$page = $parts[1];
$parts = explode($end, $page);
$fbcount = $parts[0];
if ($fbcount == '') {
    $fbcount = '0';
echo '<b> ' . $fbcount . ' </b> Subscribers';

Remove Unnecessary Widget Regions

Additional widget regions can get confusing for people if they aren’t using them. If you’re building a child theme for a client it’s a good idea to remove additional widget areas.

function hs_register_dynamic_sidebars() {
    register_sidebar( array(
        'name' => 'Sidebar One',
        'id' => 'sidebar-one',
        'description' => 'Sidebar One',
        'before_widget' => '<li id="%1$s" class="widget %2$s">',
        'after_widget' => '</li>',
        'before_title' => '<h5 class="widget-title">',
        'after_title' => '</h5>'
    register_sidebar( array(
        'name' => 'Sidebar Two',
        'id' => 'sidebar-two',
        'description' => 'Sidebar Two',
        'before_widget' => '  <li id="%1$s" class="widget %2$s">',
        'after_widget' => '</li>',
        'before_title' => '<h5 class="widget-title">',
        'after_title' => '</h5>'
add_action( 'widgets_init', 'hs_register_dynamic_sidebars' );

To unregister unwanted widget area, use code below in functions.php file.

function hs_unregister_sidebar() {
add_action( 'childtheme_sidebars', 'hs_unregister_sidebar' );

Unregister sidebar

function hs_remove_sidebar() {
add_action( 'admin_init', 'hs_remove_sidebar');

Automatically use Resized Images instead of originals

Replace your uploaded image with the large image generated by WordPress. This will save space on your server, and save bandwidth if you link your thumbnail to the original image.

Paste this into your functions.php file:

function hs_replace_uploaded_image($image_data)
    if (!isset($image_data['sizes']['large'])) {
        return $image_data;
    $upload_dir = wp_upload_dir();
    $uploaded_image_location = $upload_dir['basedir'] . '/' . $image_data['file'];
    $large_image_location = $upload_dir['path'] . '/' . $image_data['sizes']['large']['file'];
    rename($large_image_location, $uploaded_image_location);
    $image_data['width'] = $image_data['sizes']['large']['width'];
    $image_data['height'] = $image_data['sizes']['large']['height'];
    return $image_data;

add_filter('wp_generate_attachment_metadata', 'hs_replace_uploaded_image');

Detect User from Yahoo, Google and Twitter


if (strpos($_SERVER[HTTP_REFERER], "yahoo") ) {
    echo "Hello Yahoo! User!";


if (strpos($_SERVER[HTTP_REFERER], "google") == true) {
    echo "Hello Google User!";


if (strpos($_SERVER[HTTP_REFERER], "") == true) {
    echo "Hello Twitter User!";

Show Google Advert after the first post

If you want to insert an advert after the first post you can use this snippet.

<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post();
        $loopcounter++; ?>
        // the loop stuffs
        <?php if ($loopcounter <= 1) {
            include(TEMPLATEPATH . '/ad.php');
        } ?>
    <?php endwhile; ?>
<?php endif; ?>

Show adverts after the first paragraph of the post

This can be quite handy for ensuring that your advertising is up to date sitewide. Open your single.php file and find this:


Replace that code with this:

$paragraphAfter = 1; //display after the first paragraph
$content = apply_filters('the_content', get_the_content());
$content = explode("</p>", $content);

for ($i = 0; $i < count($content); $i) {

    if ($i == $paragraphAfter) { ?>
        <div>Your Text / Ads Go Here</div>
    <?php }
    echo $content[$i] . "</p>";

Show Adverts Only to Google Visitors

There are claims that visitors from search engines are more likely to click on your targeted advertisements. This snippet will let you show your adverts to visitors from Google only. Paste this into your functions.php file:

$SE = array('/search?', '', '', 'search.', '', '', '/search/', '.yahoo.');
foreach ($SE as $source) {
    if (strpos($ref, $source) !== false) {
        setcookie("sevisitor", 1, time() + 3600, "/", "");
        $sevisitor = true;
function hs_from_searchengine()
    global $sevisitor;
    if ($sevisitor == true || $_COOKIE["sevisitor"] == 1) {
        return true;
    return false;

Make sure you change to your own domain.

Place this wherever you want your ad to appear:

if (function_exists('hs_from_searchengine')) {
    if (hs_from_searchengine()) { 
        echo 'INSERT YOUR CODE HERE';

Enable Multisite

to enable Mutlisite include this in your wp-config.php

define('WP_ALLOW_MULTISITE', true); 

Show List of Recently Created Blogs

Show off all of your latest blogs. Insert into your functions.php:

function hs_get_recent_blogs($number_blogs=5)
    global $wpdb;
    /*fetch blog_id,domain,path from wp_blogs table ,where the blog is not spam,deleted or archived order by the date and time of registration */
    $query="select blog_id,domain,path from $blog_table where public='1' and archived='0' and spam='0' and deleted='0' order by registered desc limit 0,$number_blogs";
    return $recent_blogs;

Use the following to get its output:

    <ul class="recent-blogs">
        <?php $recent_blogs = hs_get_recent_blogs(5);
        foreach ($recent_blogs as $recent_blog):
            $blog_url = "";
            if (defined("VHOST") && constant("VHOST") == 'yes')
                $blog_url = "http://" . $recent_blog->domain . $recent_blog->path;
                $blog_url = "http://" . $recent_blog->domain . $recent_blog->path;
            $blog_name = get_blog_option($recent_blog->blog_id, "blogname");
                <h3><a href="<?php echo $blog_url; ?>"> </a></h3>
                <span><?php echo $blog_name ?></span>
        <?php endforeach; ?>

Change Default Gravatar

The grey mystery man is pretty boring. And those monsters aren’t much better. You can use this to change the default gravatar.

Add this code to your functions.php:

add_filter( 'avatar_defaults', 'hs_new_gravatar' );
function hs_new_gravatar ($avatar_defaults) {
    $myavatar = get_bloginfo('template_directory') . '/images/gravatar.gif';
    $avatar_defaults[$myavatar] = "Honar Systems";
    return $avatar_defaults;

Use Gravatar Hovercards

function hs_gravatar_hovercards() {
    wp_enqueue_script( 'gprofiles', '', array( 'jquery' ), 'e', true );

Show Tag Cloud

show your tag cloud.

    '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

Tiny URL

Everyone likes tiny, little URLS. Use this snippet to get them:

function hs_get_tiny_url( $url )
    $tiny_url = file_get_contents( "".$url );
    return $tiny_url;

And use this where you want.

echo hs_get_tiny_url("YOUR URL");

Prevent External Access to wp-load.php

To prevent direct access to your wp-load.php file add the following code to your .htaccess file.

<Files "wp-load.php">
  Order Deny,Allow
  Deny from all
  Allow from localhost
  Allow from

How to disable image scaling in WordPress

Add below code into your functions.php file.

add_filter( 'big_image_size_threshold', '__return_false' );