To Top

Handy Tips and Snippets for WordPress

Every day a lot of sites that are based on WordPress engine appear. Sometimes a lot of questions on how to realize different options appear in the process of blog administration. In this topic we’ve gathered the most helpful WordPress snippets that certainly will help to manage your WordPress blog.

You must always back up the site before you make any changes to the code. In case you won’t do this you might collide with plugin compatibility. It’s not worth it to take the risk,even if you are 100% sure, so here you should think twice.

Specify autosave interval

WordPress automatically saves your posts as you’re working with them. Just add this to wp-config.php for specify autosave timings:
[code]# Autosave interval set to 300 seconds #
define(‘AUTOSAVE_INTERVAL’, 300);[/code]

Simpler Login Address

You can change default login address by editing your .htaccess. Just add this before the default WordPress code:
[code]RewriteRule ^login$ [NC,L][/code]

Remove WordPress 3.1 Admin Bar

Admin bar – new function in WordPress 3.1. Don’t like it? You can remove this bar! Simply paste the following line of code on your functions.php file:
[code]remove_action(‘init’, ‘wp_admin_bar_init’);[/code]

Disable theme changing

Make sure that your client can’t switch the themes, when creating a WordPress based website. Paste the following piece of code in your functions.php file:
[code]add_action(‘admin_init’, ‘slt_lock_theme’);
function slt_lock_theme() {
global $submenu, $userdata;
if ($userdata->ID != 1) {

Remove the “read more” jump

When you click on “read more”, it automatically drops to the point in the article you theoretically just got to the end of.
It’s a bit of a pain, though. Remove it with:
[code]// no more jumping for read more link
function no_more_jumping($post) {
return ‘<a href="’.get_permalink($post->ID).’" class="read-more">’.’Continue Reading’.'</a>’;
add_filter(‘excerpt_more’, ‘no_more_jumping’);[/code]

Increase memory limit

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
[code]define(‘WP_MEMORY_LIMIT’, ’96M’);[/code]

Detect Browser

If you are using different stylesheets for different browsers theres a different way of detecting the users browsers than the HTML conditional-tags.
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;

Empty Trash Automatically

Too many spam comments? Download wp-config.php file and edit it to add below code in it.
[code]define(‘EMPTY_TRASH_DAYS’, 3 );[/code]

Limit Post Revisions

You can easily limit the number of revisions allowed by adding this to wp-config.php:
[code]# Maximum 5 revisions #
define(‘WP_POST_REVISIONS’, 5);
# Disable revisions #
define(‘WP_POST_REVISIONS’, <span id="IL_AD10" class="IL_AD">false</span>);[/code]

Show Post Time Twitter Style

Would you like to see the post dates like Twitter does, eg: 24 minutes ago, 4 hours ago etc..?
This snippet will be added to your functions.php file (so backup before you begin) and you then have a snippet which you can use where you need to see the time, for example single.php, index.php etc..
Add the following into your functions.php file, this function grabs the time and converts it into “Twitter time.”
[code]function twitter_time() {
echo "This Was Posted ".human_time_diff(get_the_time(‘U’), current_time(‘timestamp’))." ago";
This snippet can be placed wherever you need the Twitter style time to display:
[code]<?php twitter_time(); ?>[/code]

Filter the Loop

If you don’t want to show all your posts you can filter the Loop, for example in a widget with featured content that you only want to show posts from the category ‘featured’.
Simply put query_posts before the loop. All the available filters can be found in the WordPress documentation.
if ( have_posts() ) : while ( have_posts() ) : the_post();
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php the_content(); ?></p>
endwhile; else:

Loop within the loop

Call a loop within the loop by storing the original loop then reverting back to it later.
[code]if (have_posts()) :
while (have_posts()) : the_post(); // the post loop
$temp_query = $wp_query; // store it
$args = array(
‘paged’ => $paged, // paginates
‘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 Mobile Users

You can test for mobiles, then redirect to a special theme-switching URL to activate your mobile theme:
$mobile = mobile_device_detect();

if ($mobile==true) {
header( ‘Location:’ ) ;
} else {
// Do nothing, regular browser.

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.
[code]<?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
)); ?>[/code]

Change Admin Logo

Change the logo in the Admin Panel to an image of your choise.
[code]function custom_admin_logo() {
echo ‘<style type="text/css">
#header-logo { background-image: url(‘.get_bloginfo(‘template_directory’).’/images/admin_logo.png) !important; }
add_action(‘admin_head’, ‘custom_admin_logo’);[/code]
Put your logo in the image-folder and call it admin_logo.png.

Add Custom Background

Enabling custom backgrounds for your theme is very easy. Just add the line below to your theme’s functions.php file.
[code]// Add support for backgrounds

Add a Favicon to your Blog

ou can add this identity by adding the favicon code in your header.php file, or you can make it easier for yourself by simply adding the following code in your functions.php file.
[code]// add a favicon to your
function blog_favicon() {
echo ‘<link rel="Shortcut Icon" type="image/x-icon" href="’.get_bloginfo(‘wpurl’).’/favicon.ico" />’;
add_action(‘wp_head’, ‘blog_favicon’);[/code]

Remove WordPress Version Number

You can remove your WordPress version number from your WordPress header, RSS feeds, and all other locations. To do this, add the following code:
[code]function wpbeginner_remove_version() {
return ”;
add_filter(‘the_generator’, ‘wpbeginner_remove_version’);[/code]

Add Google Analytics

Click on the link for more information.
add_action(‘wp_footer’, ‘add_googleanalytics’);
function add_googleanalytics() { ?>
// Paste your Google Analytics code from Step 6 here
<?php } ?>[/code]

Highlight author comments

So you want your comments to look different that the readers? No problem. Find the list-item where the comment content is located(usually in comments.php) and add the following in the class-tag:
[code]if (1 == $comment->user_id)
echo ‘author’;[/code]

Add A Maximum Post Title Word Count

This snippet will be added to your functions.php file, so backup before you begin.
[code]function titleCount($title){
global $post;
$title = $post->post_title;
if (str_word_count($title) >= 10 )
wp_die( __(‘Error: this title is over the word limit’) );
add_action(‘publish_post’, ‘titleCount’);[/code]
This snippet will now return an error if the word count is over 10 words, you can of course alter the error message and the word count, for example if you wanted 20 words as a limit and a alternate error message.
[code]function titleCount($title){
global $post;
$title = $post->post_title;
if (str_word_count($title) >= 20 )
wp_die( __(‘Error: title over 20 words’) );
add_action(‘publish_post’, ‘titleCount’);[/code]

Automatically redirect to current page after login

WordPress have a great function named wp_login_url(). This function displays a link to your dashboard login page. It accept one parameter: an url to redirect after the user successfully logged in. By using get_permalink() as a parameter, you’ll redirect the user to the current page.
[code]<a href="<?php echo wp_login_url(get_permalink()); ?>" title="Login">Login to view</a>[/code]

Change the Footer in WordPress Admin Panel

Need to modify the dashboard footer text? Paste the following on your functions.php and save the file.
[code]function remove_footer_admin () {
echo "Your own text";

add_filter(‘admin_footer_text’, ‘remove_footer_admin’);[/code]

Stop your blog trackbacking itself

Another pet hate is trackbacks appearing when you’ve linked to something on your own site. Stop this happening with the following.
[code]//remove pings to self
function no_self_ping( &$links ) {
$home = get_option( ‘home’ );
foreach ( $links as $l => $link )
if ( 0 === strpos( $link, $home ) )
add_action( ‘pre_ping’, ‘no_self_ping’ );[/code]

Make custom post types searchable

You can add your custom post types to WordPress’ search with the following.
function searchAll( $query ) {
if ( $query->is_search ) { $query->set( ‘post_type’, array( ‘site’,’plugin’, ‘theme’,’person’ )); }
return $query;
add_filter( ‘the_search_query’, ‘searchAll’ );[/code]

Forcing A Different Theme For IE6 Users

This snippet will force IE6 users to view the default template leaving your design viewable by users with modern browsers only, thus saving time on IE6 bug fixing.
This following snippet is added to functions.php so remember to backup first.
[code]add_filter(‘template’, ‘default_ie’);
add_filter(‘option_template’, ‘default_ie’);
add_filter(‘option_stylesheet’, ‘default_ie’);
function default_ie($theme) {
if(strpos($_SERVER[‘HTTP_USER_AGENT’], ‘MSIE 6’) !== false)
$theme = ‘default’;
return $theme;

Automatically enable threaded comments

Threaded comments aren’t on by default. This can be fixed with the following.
[code]// enable threaded comments
function enable_threaded_comments(){
if (!is_admin()) {
if (is_singular() AND comments_open() AND (get_option(‘thread_comments’) == 1))
add_action(‘get_header’, ‘enable_threaded_comments’);[/code]

Remove un-needed content from the wp_head

The wp_head template tag adds a lot of “junk”. Remove it with the following!
[code]// remove junk from head
remove_action(‘wp_head’, ‘rsd_link’);
remove_action(‘wp_head’, ‘wp_generator’);
remove_action(‘wp_head’, ‘feed_links’, 2);
remove_action(‘wp_head’, ‘index_rel_link’);
remove_action(‘wp_head’, ‘wlwmanifest_link’);
remove_action(‘wp_head’, ‘feed_links_extra’, 3);
remove_action(‘wp_head’, ‘start_post_rel_link’, 10, 0);
remove_action(‘wp_head’, ‘parent_post_rel_link’, 10, 0);
remove_action(‘wp_head’, ‘adjacent_posts_rel_link’, 10, 0);[/code]

Auto Insert Content After Post

[code]function end_post($content) {
if(!is_feed() && !is_home()) {
$content.= "<h2>Enjoy this?</h2>";
$content.= "<p>Tweet about this post: etc…</p>";
return $content;
add_filter (‘the_content’, ‘end_post’);[/code]
This snippet has no functionality as it stands, so I have left it blank as the possibilities for it runs into the hundreds, simply just add the content like so:
[code]$content.= "CONTENT HERE";[/code]

Add a Custom Dashboard Logo

When creating themes for a client, you can use this as one of the perks to the theme. All you have to do is paste the following code below:
[code]//hook the administrative header output
add_action(‘admin_head’, ‘my_custom_logo’);

function my_custom_logo() {
echo ‘
<style type="text/css">
#header-logo { background-image: url(‘.get_bloginfo(‘template_directory’).’/images/custom-logo.gif) !important; }

Allow contributors to upload files

There’s an understandable security risk allowing people you don’t trust to publish content to upload media, but more often than not it’s a pain that contributors can’t upload files.
Fix it with the following.
[code]// Allow constributors to upload files
if ( current_user_can(‘contributor’) && !current_user_can(‘upload_files’) )
add_action(‘admin_init’, ‘allow_contributor_uploads’);

function allow_contributor_uploads() {
$contributor = get_role(‘contributor’);

Exclude Pages From Search Results

[code]function no_pages_in_search($query) {
if ($query->is_search) {
$query->set(‘post_type’, ‘post’);
return $query;
add_filter(‘pre_get_posts’, ‘no_pages_in_search’);[/code]
Now when you search on your blog you should have no pages show in the results, this snippet basically adds a filter on the results and removes any pages that match the search term.

Remove plugin update nag for inactive plugins

This is a pet hate of mine: the number that displays next to updates includes inactive plugins. You can change it so that you only get the number for active plugins with the following:
[code]//Remove plugin update for inactive plugins

function update_active_plugins($value = ”) {
The $value array passed in contains the list of plugins with time
marks when the last time the groups was checked for version match
The $value->reponse node contains an array of the items that are
out of date. This response node is use by the ‘Plugins’ menu
for example to indicate there are updates. Also on the actual
plugins listing to provide the yellow box below a given plugin
to indicate action is needed by the user.
if ((isset($value->response)) && (count($value->response))) {

// Get the list cut current active plugins
$active_plugins = get_option(‘active_plugins’);
if ($active_plugins) {

// Here we start to compare the $value->response
// items checking each against the active plugins list.
foreach($value->response as $plugin_idx => $plugin_item) {

// If the response item is not an active plugin then remove it.
// This will prevent WordPress from indicating the plugin needs update actions.
if (!in_array($plugin_idx, $active_plugins))
else {
// If no active plugins then ignore the inactive out of date ones.
foreach($value->response as $plugin_idx => $plugin_item) {
return $value;
add_filter(‘transient_update_plugins’, ‘update_active_plugins’); // Hook for 2.8.+
//add_filter( ‘option_update_plugins’, ‘update_active_plugins’); /[/code]

Add Shortcodes to Widgets

If you have shortcodes that you use in your WordPress blog, you might want to add them in a widget. Although this is not possible, it’s very easy to add support for it. Just add a filter in functions.php, as shown below.
[code]add_filter(‘widget_text’, ‘do_shortcode’)[/code]

Change the HTML Editor Font

Don’t like the new font used in WordPress editor in HTML mode? Change it!
[code]function change_editor_font(){
echo "<style type=’text/css’>
#editorcontainer textarea#content {
font-family: Monaco, Consolas, \"Andale Mono\", \"Dejavu Sans Mono\", monospace;
} add_action("admin_print_styles", "change_editor_font");[/code]

Add Custom User Contact Info

If there is one thing that I do not like about WordPress, it is the fact that it gives outdated options for user contact information. AIM? Yahoo? The internet has steadily moved away from these to things like Facebook and Twitter.
Copy and paste the following code into your functions.php or custom_functions.php file:
[code]/* BEGIN Custom User Contact Info */
function extra_contact_info($contactmethods) {
$contactmethods[‘facebook’] = ‘Facebook’;
$contactmethods[‘twitter’] = ‘Twitter’;
$contactmethods[‘linkedin’] = ‘LinkedIn’;
return $contactmethods;
add_filter(‘user_contactmethods’, ‘extra_contact_info’);
/* END Custom User Contact Info */[/code]
Making use of these fields is just as simple as displaying the author’s name, URL and number of posts he/she has made. We just apply a little PHP and bam, our user contact info is in use.
You can call any of these fields by using this PHP command:
[code]<a href="<?php the_author_meta(‘facebook’, $current_author->ID); ?>"></a>[/code]

Disable WordPress Search

There may be sites that you have where you don’t want users to be able to search. Use this snippet to remove the search functionality.
[code]function fb_filter_query( $query, $error = true ) {
if ( is_search() ) {
$query->is_search = false;
$query->query_vars[s] = false;
$query->query[s] = false;
// to error
if ( $error == true )
$query->is_404 = true;
add_action( ‘parse_query’, ‘fb_filter_query’ );
add_filter( ‘get_search_form’, create_function( ‘$a’, "return null;" ) );[/code]

Add Default Text to your Posts

This snippet will let you add default text that appears in every new post.

add_filter( ‘default_content’, ‘my_editor_content’ );

function my_editor_content( $content ) {

$content = "This is some custom content I’m adding to the post editor because I hate re-typing it.";

return $content;


Show Related Posts

It’s nice to be able to show your related posts – and without a plugin it’s even better.
$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();

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!
[code]// This will occur when the comment is posted
function plc_comment_post( $incoming_comment ) {
// convert everything in a comment to display literally
$incoming_comment[‘comment_content’] = htmlspecialchars($incoming_comment[‘comment_content’]);
// the one exception is single quotes, which cannot be #039; because WordPress marks it as spam
$incoming_comment[‘comment_content’] = str_replace( "’", ”’, $incoming_comment[‘comment_content’] );
return( $incoming_comment );
// This will occur before a comment is displayed
function plc_comment_display( $comment_to_display ) {
// Put the single quotes back in
$comment_to_display = str_replace( ”’, "’", $comment_to_display );

return $comment_to_display;
add_filter( ‘preprocess_comment’, ‘plc_comment_post’, ”, 1);
add_filter( ‘comment_text’, ‘plc_comment_display’, ”, 1);
add_filter( ‘comment_text_rss’, ‘plc_comment_display’, ”, 1);
add_filter( ‘comment_excerpt’, ‘plc_comment_display’, ”, 1);[/code]

Remove autolinks in comments

To remove automatic linking of urls in comments, simply open your functions.php file and paste the following:
[code]remove_filter(‘comment_text’, ‘make_clickable’, 9);[/code]

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.
[code]define(‘FORCE_SSL_ADMIN’, true);[/code]

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. Make sure to put in your new username.
[code]UPDATE wp_users SET user_login = ‘Your New Username’ WHERE user_login = ‘Admin’;[/code]

Remove the WordPress version

Add this to your functions.php file:
[code]function no_generator() { return ”; }
add_filter( ‘the_generator’, ‘no_generator’ );[/code]

Protect your wp-config.php

Your wp-config.php file contains your blogs database details and other pieces of info about your blog a potential hacker would like to see, so inside your .htaccess file add:
[code]<Files wp-config.php>
order allow,deny
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.
[code]# Disable access to wp-admin for Subscribers

if ( is_user_logged_in() &amp;&amp; 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/’ );

Tiny URL

Everyone likes tiny, little URLS. Use this snippet to get them:
[code]function get_tiny_url( $url )
$tiny_url = file_get_contents( "".$url );

return $tiny_url;

Add custom menu items to admin favorites menu

Adding this snippet to the functions.php of your wordpress theme will add new menu items to the wordpress admin favorites menu. If you want to sort the menu items alphabetically uncomment out line 05 just remove the two slashes // and you are done.
[code]function favorites_menu_items($actions) {
$actions[‘plugins.php’] = array(‘Plugins’, ‘activate_plugins’);
$actions[‘plugin-install.php’] = array(‘Plugin Add new’, ‘activate_plugins’);
$actions[‘plugin-editor.php’] = array(‘Plugin editor’, ‘activate_plugins’);
// asort($actions);
return $actions;
add_filter(‘favorite_actions’, ‘favorites_menu_items’);

Attachment window hide buttons and input fields

Adding this snippet to the functions.php of your wordpress theme will allow you to hide buttons and input fields within the media attachment window.
[code]function attachment_fields($form_fields, $post) {
if ( substr( $post->post_mime_type, 0, 5 ) == ‘image’ ) {
$form_fields[‘image_alt’][‘value’] = ”;
$form_fields[‘image_alt’][‘input’] = ‘hidden’;
$form_fields[‘post_excerpt’][‘value’] = ”;
$form_fields[‘post_excerpt’][‘input’] = ‘hidden’;
$form_fields[‘post_content’][‘value’] = ”;
$form_fields[‘post_content’][‘input’] = ‘hidden’;
$form_fields[‘url’][‘value’] = ”;
$form_fields[‘url’][‘input’] = ‘hidden’;
$form_fields[‘align’][‘value’] = ‘aligncenter’;
$form_fields[‘align’][‘input’] = ‘hidden’;
$form_fields[‘image-size’][‘value’] = ‘thumbnail’;
$form_fields[‘image-size’][‘input’] = ‘hidden’;
$form_fields[‘image-caption’][‘value’] = ‘caption’;
$form_fields[‘image-caption’][‘input’] = ‘hidden’;
$form_fields[‘buttons’][‘input’] = ‘hidden’;
return $form_fields;
add_filter(‘attachment_fields_to_edit’, ‘attachment_fields’, 15, 2 );

Automatically create meta description from the_content

Adding this snippet to the functions.php of your wordpress theme will automatically create a meta description from your wordpress post striping out all shortcodes and tags.
[code]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’);

How to Redirect Users After They Update Their Profiles in WordPress

[code]add_action( ‘profile_update’, ‘custom_profile_redirect’, 12 );
function custom_profile_redirect() {
if ( current_user_can( ‘subscriber’ ) ) {
wp_redirect( trailingslashit( home_url() ) );

More inSplashnology

Privacy Preference Center