Wordpress Tweaks   Change the Layout of Your WordPress Pages

25 WordPress Tweaks to Improve Page Layout and Performance

If you are reading this article then most probably you have used the WordPress or know about it very well. The most robust CMS for bloggers and business websites to the date, WordPress tries to bring something new with its every new release, latest is version 3.3.2. WordPress tries to bring the most secure environment for your blogs and websites and with the performance boost off-course. Despite getting near to perfect settings from WordPress, we, sometime, try to get more suitable according to our need.

This article is all about these WordPress customize settings, we will tell you some superb WordPress tweaks to change the look and feel of its post and pages. As you know uniqueness and attractiveness is the basic element to catch visitors toward your website. 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.

 

1. Allow More HTML Tags In The Editor

WordPress editor doesn’t allow HTML tags which aren’t compliant with the XHTML 1.0 standard. Change the functions.php file and paste the following code to force the editor to accept more tags.

function fb_change_mce_options($initArray) {  
    // Comma separated string od extendes tags  
    // Command 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 paramter verify_html  
    //$initArray['verify_html'] = false;  
    return $initArray;  
}  
add_filter('tiny_mce_before_init', 'fb_change_mce_options');  

Source

 

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

Source

 

3. Allow Upload Of More File Types

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.

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

Source

 

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

Source

 

5. 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, use the following function and add this to the functions.php file.

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

Source

 

6. 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>';  
}  

Source

 

7. How To Change WordPress Editor Font

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

Source

 

8. 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);  
    }  
}  

Source

 

9. Change Excerpt Length Depending Of The Category

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;  
    }  
}  

Source

 

10. Disable Posts Auto Saving

It’s possible to restrict wordpress from Auto Saving your post while in editing mode, simply paste the following function into functions.php file and save the file.

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

Source

 

11. 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;  
}  

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  
    }  
}

Source

 

12. 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>  

Source

 

13. Set Post Expiration Date/Time

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. 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.

<?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;  
?>  

Source

 

14. Create Your Own Popular Posts In The Sidebar

Just copy and paste the code below into your sidebar.php file.

<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>  

Source

 

15. 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.

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

Source

 

16. 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 ) );  
        }  
    }  
}  

Source

 

17. Exclude Post From WordPress Feed

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

Source

 

18. Display Post 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'); 

Source

 

19. Twitter Style “Time Ago” Dates

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

Source

 

20. Change Your Excerpt Length

he 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 100 as the excerpt length.

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

Source

 

21. 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 ( emptyempty($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 = !emptyempty($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 ( emptyempty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s'] )  
  $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";  
  if ( !emptyempty($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 ); 

Source

 

22. 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.

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

Source

 

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

Source

 

24. Automatically Replace Words By Affiliate Links

To replace words by affiliate links automatically, simply paste the code below into your functions.php file.

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

Source

 

25. Show Related Posts Without A Plugin

You need to place the following code 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>';  
        }  
    }  
?> 

Source

Like This Post ♥

  4 Like

Written by Bono

A Computer Applications Geek, hooked on all things pertaining to Web Development & Design, intent on delivering you the best in Web content to simplify your Blogging Experience.

Comments

2 Comments on "25 WordPress Tweaks to Improve Page Layout and Performance"

  1. Thad says:

    Useful post. Thanks. I’ll be using some of these.

  2. Raj says:

    I have a query for you, how does the code provided for Popular Posts work, is based on views or its based on comments..?


Here's your chance to leave a comment!

HTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>