29 WordPress Tweaks to Enhance Posts and Pages

WordPress is a fantastic CMS, but sometimes its default settings, especially how posts are displayed, might not fit everyone’s needs. Personalizing your website is key to creating a unique brand and making a lasting impression on your visitors. Over the years, both bloggers and developers have worked hard to customize the display of posts to make each site stand out.

In this article, we’ll explore a range of clever modifications you can apply to enhance your WordPress posts. These tweaks are perfect for anyone aiming to improve user experience, boost revenue, or increase page views. The best part? Most of these adjustments don’t require a plugin. They are straightforward to implement — usually, it’s just a matter of copying and pasting the code we provide.

Whether you’re working on a personal project or a professional one, these tweaks are here to help you refine your site. So, let’s dive into customizing your WordPress experience!

Tweaks for the WordPress Front-End

1. Change Your Excerpt Length

The tweak below will change your excerpt length, and 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. Display Dates in a Twitter-Style “Time Ago” Format

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.

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

3. Include Post Thumbnails 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. Restrict Search to Post Titles Only

You can add this snippet into the functions.php file of your WordPress Themes 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 Incremental 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 a Post from the 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 Yields a 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));
            exit;
        }
    }
}

8. Automatically Generate Meta Descriptions 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 with 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 a "Read More" Permalink at 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 '... ' . 'Read More' . '';
}
add_filter('excerpt_more', 'excerpt_readmore');
11. Display Related Posts Without Using 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 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 a Post Expiration Date/Time

Below is a useful code that you can put into your WordPress Themes 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 example... 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 your 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. Show AdSense Only to Search Engine Visitors

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.

if (function_exists('scratch99_fromasearchengine')) {
    if (scratch99_fromasearchengine()) {
        INSERT YOUR CODE HERE
    }
}

Tweaks for WordPress Backend”

1. Enable Additional 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.

function fb_change_mce_options($initArray) {
    // Comma separated string of extended tags
    // Comma separated string of extended elements
    $ext = 'pre[id|name|class|style],iframe[align|longdesc|name|width|height|frameborder|scrolling|marginheight|marginwidth|src]';
    if (isset($initArray['extended_valid_elements'])) {
        $initArray['extended_valid_elements'] .= ',' . $ext;
    } else {
        $initArray['extended_valid_elements'] = $ext;
    }
    
    // maybe; set tiny parameter verify_html
    //$initArray['verify_html'] = false;
    return $initArray;
}
add_filter('tiny_mce_before_init', 'fb_change_mce_options');
2. Set the 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. Apply Different Editor Stylesheets for Various 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 the Upload of Additional 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 (|).


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 Excerpts

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(){ ?>
    

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>

add_action('admin_head-post.php', 'tinymce_css');
add_action('admin_head-post-new.php', 'tinymce_css');
6. Post Formats: Creative Options for Themes

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. Show Post Thumbnails in Edit Post and Page Overviews

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 page
    add_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 Panel

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];
    $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;
    }
    .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. Limit 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. Change the Font in the WordPress Editor

Hate the current font used in WordPress editor? It’s possible to be changed to a 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. Automatically Add a Custom Field Upon Post/Page Publication

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. Remove 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. Vary Excerpt Length Based on 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 Automatic Post 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 deleting the code.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail