WordPress-Domain-Transfer

Tweaks to Improve WordPress 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.

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) . '">' . '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><?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.

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

Related Posts


One thought on “Tweaks to Improve WordPress Posts and Pages

  1. no hands seo

    Many thanks for some other helpful web-site. Where by different may I recieve that sort of info designed in such a great manner? I own a difficult task that i am right now managing upon, and i have been recently on the watch out for similarly info.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


*