29 WordPress Tweaks to Improve Posts and Pages

We love WordPress – but not all of us are ready to settle with all its default settings and displays – particularly how posts are displayed. As we’re taught that uniqueness does matter to a website’s branding which gives the visitors a great impression, throughout these years bloggers and developers have been striving to tweak the post display, in order to make it as unique as possible.

wordpress tweaks
(Image Source: Fotolia, WordPress)

Today we are going to focus on the smart tweaks you can perform to improve your WordPress post display. Whether you are looking to change your post display to enhance user experience or to increase revenue or page impressions, chances are there is a way to do it without plugin, and most of the snippets listed here are easy to implement, in most time you just need to copy and paste the provided code.

Hope you will find these tweaks useful for your projects, enjoy customizing!


Front End

1. Change your excerpt length

The tweak below will change your excerpt length, which you can just add the following lines of code into your functions.php file, with the value 75 as the excerpt length.

add_filter('excerpt_length', 'my_excerpt_length');
function my_excerpt_length($len) { return 75; }

2. Twitter style “time ago” dates

Most people don’t know that WordPress has a built-in function to display the date using the “Time Ago” format, and the snippet below can be pasted to anywhere within the loop to display the date with the format.

Posted <?php echo human_time_diff(get_the_time('U'), current_time('timestamp')) . ' ago';

3. Display post thumbnail in your RSS feed

Introduced in WordPress 2.9, the the_post_thumbnail() function is very useful to add and display a thumbnail attached to a post. The bad news is there’s no built-in method to display the thumbnail in your RSS feed. The function below will solve this problem. Simply paste it into your functions.php file, save it, and the post thumbnail will be automatically displayed in your RSS feed.

// show post thumbnails in feeds
function diw_post_thumbnail_feeds($content) {   global $post;   if(has_post_thumbnail($post->ID)) {      $content = '<div>' . get_the_post_thumbnail($post->ID) . '</div>' . $content;    }   return $content;}add_filter('the_excerpt_rss', 'diw_post_thumbnail_feeds');add_filter('the_content_feed', 'diw_post_thumbnail_feeds');


4. Limit search to post titles only

You can add this snippet into the functions.php file of your WordPress theme to limit the search to post titles only.

function __search_by_title_only( $search, &$wp_query )
if ( empty($search) )
return $search; // skip processing - no search term in query
$q =& $wp_query->query_vars;

// wp-includes/query.php line 2128 (version 3.1)
$n = !empty($q['exact']) ? '' : '%';
$searchand = '';
foreach( (array) $q['search_terms'] as $term ) {
$term = esc_sql( like_escape( $term ) );
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
$searchand = ' AND ';
$term = esc_sql( like_escape( $q['s'] ) );
if ( empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s'] )
$search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
if ( !empty($search) ) {
$search = " AND ({$search}) ";
if ( !is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = '') ";
return $search;
add_filter( 'posts_search', '__search_by_title_only', 10, 2 );

5. Display an incrementing number on each post

The tweak below will let you display an incrementing number on each post, and implementing it is pretty simple. First, paste the following function into your functions.php file:

function updateNumbers() { 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): setup_postdata($post); $counts++; add_post_meta($post->ID, 'incr_number', $counts, true); update_post_meta($post->ID, 'incr_number', $counts); endforeach; endif; } add_action ( 'publish_post', 'updateNumbers' ); add_action ( 'deleted_post', 'updateNumbers' ); add_action ( 'edit_post', 'updateNumbers' );

Once you’re done, you can display the post number with the following code. Note that it has to be used within the loop.

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

6. Exclude Post from WordPress Feed

Looking to exclude certain posts from your feed? Here’s the tweak for you. Please be noted that you should only filter where you want to filter; in our example it is in our feed $wp_query->is_feed. If you didn’t make it that way, the filter would also run in your back end and these posts won’t be shown on post overview.

The function has two parameters. You give the first parameter $where an extension of the SQL string, which will be taking care of the filtering based on the ID. Then, within the brackets you need to insert the IDs of the posts, which you like to filter.

function fb_post_exclude($where, $wp_query = NULL) { global $wpdb; if ( !$wp_query ) global $wp_query; if ($wp_query->is_feed) { // exclude post with id 40 and 9 $where .= " AND $wpdb->posts.ID NOT IN (40, 9)"; } return $where; } add_filter( 'posts_where','fb_post_exclude', 1, 2 );

7. Redirect to post when search query returns single result

Put this snippet into the functions.php file of your WordPress theme to redirect your search to the post automatically when WordPress only returns a single search result.

add_action('template_redirect', 'single_result'); function single_result() { if (is_search()) { global $wp_query; if ($wp_query->post_count == 1) { wp_redirect( get_permalink( $wp_query->posts['0']->ID ) ); } } }

8. Automatically create meta description from the_content

Adding this snippet into the functions.php file of your WordPress theme will automatically create a meta description from your WordPress post, striping out all shortcodes and tags. Also ensure that you have it in the header.php of your WordPress theme or this snippet will not function.

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');

9. Automatically replace words by affiliate links

To replace words by affiliate links automatically, simply paste the code below into your functions.php file. Remember to enter your words/links as shown in the example code below.

function replace_text_wps($text){ $replace = array( // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS' 'thesis' => '<a href="http://mysite.com/myafflink">thesis</a>', 'studiopress' => '<a href="http://mysite.com/myafflink">studiopress</a>' ); $text = str_replace(array_keys($replace), $replace, $text); return $text; } add_filter('the_content', 'replace_text_wps'); add_filter('the_excerpt', 'replace_text_wps');

10. Add “Read More” permalink to the end of the_excerpt

Adding this snippet below into the functions.php file of your WordPress theme will add a “read more” permalink at the end of the_excerpt, pretty much like what the_content does.

function excerpt_readmore($more) { return '... <a href="'. get_permalink($post->ID) . '" class="readmore">' . 'Read More' . '</a>'; } add_filter('excerpt_more', 'excerpt_readmore');

11. Show related posts without a plugin

Installing the code below will make your WordPress site display related posts based on the current post tag(s). You need to place it inside single.php, or simply anywhere you want to show the related posts.

<?php $tags = wp_get_post_tags($post->ID); if ($tags) { $tag_ids = array(); foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id; $args=array( 'tag__in' => $tag_ids, 'post__not_in' => array($post->ID), 'showposts'=>5, // Number of related posts that will be shown. 'caller_get_posts'=>1 ); $my_query = new wp_query($args); if( $my_query->have_posts() ) { echo '<h3>Related Posts</h3><ul>'; 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 } echo '</ul>'; } } ?>

12. Create Your Own Popular Posts in the Sidebar

Setting up a sidebar widget to display popular posts is very easy. Just copy and paste the code below into your sidebar.php file. If you need to change the number of posts shown, you can change the 5 at the end of line 3 to any number you prefer.

<h2>Popular Posts</h2> <ul> <?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5"); foreach ($result as $post) { setup_postdata($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 ?>}</li> <?php } } ?> </ul>

13. Set post expiration Date/Time

Below is a useful code that you can put into your WordPress theme to enable the possibility of creating post expiration based on date and time. Edit your theme and replace your current WordPress loop with this “hacked” loop:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?> $expirationtime = get_post_custom_values('expiration'); if (is_array($expirationtime)) { $expirestring = implode($expirationtime); } $secondsbetween = strtotime($expirestring)-time(); if ( $secondsbetween > 0 ) { // For exemple...   the_title(); the_excerpt(); } endwhile; endif; ?>
To create a post with date/time expiration, you can just create a custom field. Give expiration as a key and your date/time (format: mm/dd/yyyy 00:00:00) as a value. The post will not show up after that particular timestamp.

14. List future posts

WordPress allows listing future posts, and to achieve this feature, simply paste the code to wherever you’d like you future posts to be displayed:

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

15. Display AdSense to search engines visitors only

It’s possible to display the AdSense to the visitors from search engines’ results, and here’s the code to achieve it, just paste the code below into the theme’s functions.php file.

function scratch99_fromasearchengine(){ $ref = $_SERVER['HTTP_REFERER']; $SE = array('/search?', 'images.google.', 'web.info.com', 'search.', 'del.icio.us/search', 'soso.com', '/search/', '.yahoo.'); foreach ($SE as $source) { if (strpos($ref,$source)!==false) return true; } return false; }

$SE array is where you specify the search engines. You can add new search engine by adding new element to the array, then just paste the following code anywhere in the template where you want your AdSense ads to be displayed, and it’s done! The ads will only be displayed to visitors from search engines’ results.

  1. if (function_exists('scratch99_fromasearchengine')) {
  2.     if (scratch99_fromasearchengine()) {
  4.     }
  5. }

Back End

1. Allow more HTML tags in the editor

By default, WordPress editor doesn’t allow HTML tags which aren’t compliant with the XHTML 1.0 standard. However, the code shown below will force the editor to accept more tags. You can paste it into your theme’s functions.php file, save it, and the function is good to go.

  1. function fb_change_mce_options($initArray) {
  2.     // Comma separated string od extendes tags
  3.     // Command separated string of extended elements
  4.     $ext = 'pre[id|name|class|style],iframe[align|longdesc|name|width|height|frameborder|scrolling|marginheight|marginwidth|src]';
  5.     if ( isset( $initArray['extended_valid_elements'] ) ) {
  6.     $initArray['extended_valid_elements'] .= ',' . $ext;
  7.     } else {
  8.         $initArray['extended_valid_elements'] = $ext;
  9.     }
  10.     // maybe; set tiny paramter verify_html
  11.     //$initArray['verify_html'] = false;
  12.     return $initArray;
  13. }
  14. add_filter('tiny_mce_before_init', 'fb_change_mce_options');

2. Set default editor

Snippet below modifies the default editor in WordPress admin. You can go with the Visual Editor, or you can choose the HTML Editor, just add one of them into the functions.php file.

# 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";') );

3. Set different editor stylesheets for different post types

With the following code pasted into your functions.php file, you can setup different editor stylesheets for different post types. You will need to adapt it, depending on your post types, and remember to change the stylesheets names as well.

function my_editor_style() { global $current_screen; switch ($current_screen->post_type) { case 'post': add_editor_style('editor-style-post.css'); break; case 'page': add_editor_style('editor-style-page.css'); break; case 'portfolio': add_editor_style('editor-style-portfolio.css'); break; } } add_action( 'admin_head', 'my_editor_style' );

4. allow upload of more file types

For certain reason, WordPress Uploader won’t let you upload certain file types, such as Textmate’s .tmCommand. If you need to upload those kinds of files to your WordPress site, here comes a functional snippet that allows you to do it, and you just need to paste it into your functions.php file. You can also add more file types by adding them on line 4, separated by a pipe (|).

<?php function addUploadMimes($mimes) { $mimes = array_merge($mimes, array( 'tmbundle|tmCommand|tmDragCommand|tmSnippet|tmLanguage|tmPreferences' => 'application/octet-stream' )); return $mimes; } ?> add_filter('upload_mimes', 'addUploadMimes');

5. Enable TinyMCE editor for post the_excerpt

Putting the following snippet into the functions.php file of your WordPress theme will add the TinyMCE editor to the post excerpt’s textarea.

function tinymce_excerpt_js(){ ?> <script type="text/javascript"> jQuery(document).ready( tinymce_excerpt ); function tinymce_excerpt() { jQuery("#excerpt").addClass("mceEditor"); tinyMCE.execCommand("mceAddControl", false, "excerpt"); } </script> <?php } add_action( 'admin_head-post.php', 'tinymce_excerpt_js'); add_action( 'admin_head-post-new.php', 'tinymce_excerpt_js'); function tinymce_css(){ ?> <style type='text/css'> #postexcerpt .inside{margin:0;padding:0;background:#fff;} #postexcerpt .inside p{padding:0px 0px 5px 10px;} #postexcerpt #excerpteditorcontainer { border-style: solid; padding: 0; } </style> <?php } add_action( 'admin_head-post.php', 'tinymce_css'); add_action( 'admin_head-post-new.php', 'tinymce_css');

6. Post Formats – More Creative Ways For A Theme

The syntax below gives some of the possible post formats which can then be chosen and used directly in the article, and what you need to do is to put the code into your functions.php file of your theme.

add_theme_support( 'post-formats', array( 'aside', 'audio', 'image', 'video' ) );

7. Display Post Thumbnail Also In Edit Post and Page Overview

WordPress version 2.9 introduced the function of Post Thumbnail. It’s quite awesome, and to display post thumbnail also in Edit Post and Page Overview, you can put the following code into a Plugin or copy them into the functions.php file of the theme.

if ( !function_exists('fb_AddThumbColumn') && function_exists('add_theme_support') ) { // for post and pageadd_theme_support('post-thumbnails', array( 'post', 'page' ) ); function fb_AddThumbColumn($cols) { $cols['thumbnail'] = __('Thumbnail'); return $cols; } function fb_AddThumbValue($column_name, $post_id) { $width = (int) 35; $height = (int) 35; if ( 'thumbnail' == $column_name ) { // thumbnail of WP 2.9 $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true ); // image from gallery $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') ); if ($thumbnail_id) $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true ); elseif ($attachments) { foreach ( $attachments as $attachment_id => $attachment ) { $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true ); } } if ( isset($thumb) && $thumb ) { echo $thumb; } else { echo __('None'); } } } // for posts add_filter( 'manage_posts_columns', 'fb_AddThumbColumn' ); add_action( 'manage_posts_custom_column', 'fb_AddThumbValue', 10, 2 ); // for pages add_filter( 'manage_pages_columns', 'fb_AddThumbColumn' ); add_action( 'manage_pages_custom_column', 'fb_AddThumbValue', 10, 2 ); }

8. Create custom post status messages in admin

This tweak was originally written by the developer as a way for a client to display custom messages for each post an author creates. In this case a post could have a message as rejected, error, source, final, etc. You can change the messages just below the code’s comment, Array of custom status messages, just to ensure that you changed the class names as well, which you can change them after the comment, change color of messages below.

add_filter('display_post_states', 'custom_post_state'); function custom_post_state($states) { global $post; $show_custom_state = get_post_meta($post->ID, '_status'); if ($show_custom_state) { $states[] = __('<span class="custom_state ' . strtolower($show_custom_state[0]) . '">' . $show_custom_state[0] . '</span>'); } return $states; } add_action('post_submitbox_misc_actions', 'custom_status_metabox'); function custom_status_metabox() { global $post; $custom = get_post_custom($post->ID); $status = $custom["_status"][0]; $i = 0; /* ----------------------------------- */ /*   Array of custom status messages            */ /* ----------------------------------- */ $custom_status = array('Spelling', 'Review', 'Errors', 'Source', 'Rejected', 'Final', ); echo '<div class="misc-pub-section custom">'; echo '<label>Custom status: </label><select name="status">'; echo '<option class="default">Custom status</option>'; echo '<option>-----------------</option>'; for ($i = 0; $i < count($custom_status); $i++) { if ($status == $custom_status[$i]) { echo '<option value="' . $custom_status[$i] . '" selected="true">' . $custom_status[$i] . '</option>'; } else { echo '<option value="' . $custom_status[$i] . '">' . $custom_status[$i] . '</option>'; } } echo '</select>'; echo '<br /></div>'; } add_action('save_post', 'save_status'); function save_status() { global $post; if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post->ID; } update_post_meta($post->ID, "_status", $_POST["status"]); } add_action('admin_head', 'status_css'); function status_css() { echo '<style type="text/css"> .default{font-weight:bold;} .custom{border-top:solid 1px #e5e5e5;} .custom_state{ font-size:9px; color:#666; background:#e5e5e5; padding:3px 6px 3px 6px; -moz-border-radius:3px; } /* ----------------------------------- */ /*   change color of messages below            */ /* ----------------------------------- */ .spelling{background:#4BC8EB;color:#fff;} .review{background:#CB4BEB;color:#fff;} .errors{background:#FF0000;color:#fff;} .source{background:#D7E01F;color:#333;} .rejected{background:#000000;color:#fff;} .final{background:#DE9414;color:#333;} </style>'; }

9. Set maximum post title length

Adding this PHP code into the functions.php file of your WordPress theme will set a maximum number of words that can be displayed within your post title, quite handy tweaks!

function maxWord($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', 'maxWord');

10. How to change WordPress editor font

Hate the current font used in WordPress editor? It’s possible to be changed to modern font such as Monaco or Consolas, just paste the code into your WordPress theme‘s functions.php file.

function change_editor_font(){ echo "<style type='text/css'> #editorcontainer textarea#content { font-family: Monaco, Consolas, "Andale Mono", "Dejavu Sans Mono", monospace; font-size:14px; color:#333; } </style>"; } add_action("admin_print_styles", "change_editor_font");

11. Adding A Custom Field Automatically On Post/Page Publish

A code snippet for installing a custom field automatically to a page or post when they are published. You can just add the code below into your functions.php file, located inside your theme’s folder. Of course, don’t forget to change the custom field name.

add_action('publish_page', 'add_custom_field_automatically'); add_action('publish_post', 'add_custom_field_automatically'); function add_custom_field_automatically($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { add_post_meta($post_ID, 'field-name', 'custom value', true); } }

12. Get rid of unused post revisions

Here comes a very handy SQL query that will delete all posts revisions instantly as well as meta associated with it. You’ve to run the following query on your WordPress database, and all revisions (as well as meta associated with it) will be deleted from your database. One important note here, be sure to make a backup of your database before you run the code.

DELETE a,b,c
FROM wp_posts a
WHERE a.post_type = 'revision'
LEFT JOIN wp_term_relationships b
ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id);

13. Change excerpt length depending of the category

Ever wished to modify the excerpt length based on which category you are on? Here comes the code which grants your wish. Simply paste the code into your functions.php file, and don’t forget to change the category ID on line 3!

add_filter('excerpt_length', 'my_excerpt_length'); function my_excerpt_length($length) { if(in_category(14)) { return 13; } else { return 60; } }

14. Disable posts auto saving

If for some critical reason you’d like to disable the function that autosaves your post while you’re editing it in the dashboard, it’s possible. Simply open your functions.php file and paste the following code into the file:

function disableAutoSave(){ wp_deregister_script('autosave'); } add_action( 'wp_print_scripts', 'disableAutoSave' );

You can then save the file, and WordPress will never autosave a post. You can also get the function back by delete the code.

Shree Tapasya

Sumeet Kalsey is a WordPress fanatic and loves experimenting with WordPress themes & plugins.
Also Search for new contents and software's in free time. Get more from Kalsey on
& Facebook

Shree Tapasya

Sumeet Kalsey is a WordPress fanatic and loves experimenting with WordPress themes & plugins. Also Search for new contents and software's in free time. Get more from Kalsey on Google+ & Facebook

No comments yet.

Leave a Reply