We all want to get the most out of every website we run – and WordPress is no exception. When we first started this site, there were many things we couldn’t figure out and we had to go it alone.
We want to make sure you jumpstart your learning process and get the most out of WordPress right now!
With WordPress being the CMS of choice for 40% of the top 10K sites, and with it being the CMS of choice for 50% of the entire Internet, we’re sure we speak for many people when we say these WordPress tips will help you push WordPress blog to its full potential!
The great thing about WordPress is that it’s popularity has led to a large amount of tips and tutorials available which can show you how to do lots of stuff, small WordPress tricks which push your website to it’s maximum potential. WordPress has matured significantly over the years, from a humble blog to a CMS that is so flexible that it allows you to create any kind of websites today. From a personal blog to e-commerce site to niche social network, you can count on WordPress and all kinds of WordPress themes to allow you to create a great website.
And with the growth comes the need of WordPress tricks or “hacks” – small changes in the WordPress code to optimize the performance and display of WordPress.
However, most WordPress users are not developers and do not have much experience with code. Thus, many people are not able to use WordPress tricks to tweak and optimize their WordPress sites to add more functionality.
In this article we’ll show you how to do some cool tips on WordPress without hiring a developer – these are a few simple WordPress tricks (or small tweaks/changes in WordPress code) which allow you to get more, much more from your WordPress website installation.
Why do we call these tricks or hacks? Wikipedia defines a programming hack as “an inelegant but effective solution to a computing problem”. So since we are changing the WordPress files – we are calling these changes hacks – essentially it’s just WordPress tips and tricks which you should use to make your overall WordPress experience healthier without having to go through a a huge amount of WordPress tutorials..
Note: This article assumes you know that some basic HTML/CSS coding. In addition, make sure you backup the files before making any tweaks on it.
Table of contents for 101 WordPress tips tricks and tweaks
I. Add features
II. Community tricks
III. Analytics tricks
IV. Monetization tricks
V. Security tricks
VI. SEO tricks
VII. Social media tricks
Wordpress tricks to add features
Add new features to your WordPress site using the following tricks tips and tweaks.
1. Add one or more footer widget areas
Not every WordPress websites support footer widgets. So this tweak will help you add multiple footer widgets into your WordPress theme. Read the tutorial here.
2. Customize log in page
Adding a few tweaks on your functions.php file will let you customize your log in page. Here’s what you need to do.
a) In your current theme directory (../wp-content/themes/your-theme-name), add a folder called “login”. Create a css file inside the login folder and name it custom-login-styles.css
b) Next, add the following code into your functions.php file
function my_custom_login() {
echo ‘<link rel=”stylesheet” type=”text/css” href=”‘ . get_bloginfo(‘stylesheet_directory’) . ‘/login/custom-login-styles.css” />’;
}
add_action(‘login_head’, ‘my_custom_login’);
Simply customize your CSS file, custom-login-styles.css. This will reflect on the log in page.
3. Add custom page into WordPress
It is possible to custom design a page with simple HTML/CSS, and installs it to your WordPress site. All that needed is to simply add the following code into the top of your custom HTML page.
<?php /* Template Name: Squeeze */ ?>
After adding the code, save the page as squeeze.php and upload it to your current theme folder (../wp-content/themes/your-theme-name).
Once the file is uploaded, create a new page and choose the template Squeeze under ‘Page Attributes’. Publish the page to see it live.
4. Add infinite scroll WordPress trick
Automatically load new content when the reader scrolls down and approaches the bottom of the page. Actually infinite scroll is a Jetpack plugin feature. If you’re using a well coded theme like the default WordPress theme, your theme will support infinite scroll.
Install the Jetpack plugin, enable infinite scroll feature and add the following code to yourfunctions.php file.
add_theme_support( ‘infinite-scroll’, array(
‘container’ => ‘content’,
‘footer’ => ‘page’,
) );
5. Disable post revisions
‘Post revisions’ is one of the best WordPress features. However, some users might not need this feature especially for those who have limited database space.
To disable the feature, add the following code to wp-config.php file
define(‘AUTOSAVE_INTERVAL’, 120 ); // seconds
define(‘WP_POST_REVISIONS’, false );
This code will disable all the future revisions, and it extends the autosave interval from 60 to 120 seconds. It means your post will be autosaving every 120 seconds.
6. Add customized CSS file
Add a customized CSS file with the name ‘custom.css’ to your theme by adding the following code to your functions.php file.
function custom_style_sheet() {
wp_enqueue_style( ‘custom-styling’, get_stylesheet_directory_uri() . ‘/custom.css’ );
}
add_action(‘wp_enqueue_scripts’, ‘custom_style_sheet’);
Make sure the new CSS file is located on the same directory that of main CSS file.
7. Install child theme
Create a child theme and add the below code to the CSS file of your child theme.
/*
Theme Name: Child Theme Name
Template: parenttheme
*/
@import url(“../parenttheme/style.css”);
Make sure you change parenttheme to the actual name of the parent theme and call the parent theme’s CSS file within your child theme’s CSS file37. Use normal quotes instead of curly quotes. We also have a detailed tutorial on how to add a child theme and widget area here.
8. Use normal quotes instead of curly quotes
If you have ever shared a code snippet on WordPress, you might have noted that by default, WordPress turns normal quotes to smart codes, which could break the code snippet you’re about to publish.
To disable this feature, insert the following code snippet to your functions.php file
remove_filter(‘the_content’, ‘wptexturize’);
9. Display random image header
If you are a person who would love to display random image headers on your blog, this trick is for you.
Name your image 1.jpg, 2.jpg, 3.jpg, and so on. Upload those images to images folder inside your theme directory. Then, paste the following code to the header.php file.
<img src=”http://Path_to_image_
folder/<?php echo(rand(1,10)); ?>.jpg” width=”image_width” height=”image_height” alt=”image_alt_text” />
Make sure you replace the Path_to_image_folder with the actual path.
10. Delete existing post revisions
If you want not only to disable the post revision but also to delete all the existing revisions saved in your database, simply run the following SQL query from your PHPMyAdmin.
DELETE FROM wp_posts WHERE post_type = ‘revision’;
11. Add featured box inside the content
If you would like to add a featured box inside your post that stands out from the rest of the content, add the following code to the theme’s functions.php file.
function make_yellowbox($atts, $content = null) {
return ‘<p style=”background: none repeat scroll 0 0 #ff9; clear: both; margin-bottom: 18px; overflow: hidden; border: 1px solid #e5e597; padding: 13px;”>’ . do_shortcode($content) . ‘</p>’;
}
add_shortcode(‘yellowbox’, ‘make_yellowbox’);
Once the code is added, any text wrapped inside the shortcode will appear in a featured yellow colored box.
[yellowbox]Your featured content here[/yellowbox]
12. Show related posts
Insert the below code to single.php file to show related posts without a plugin.
<?php //for use in the loop, list 5 post titles related to first tag on current post
$backup = $post; // backup the current object
$tags = wp_get_post_tags($post->ID);
$tagIDs = array();
if ($tags) {
$tagcount = count($tags);
for ($i = 0; $i < $tagcount; $i++) {
$tagIDs[$i] = $tags[$i]->term_id;
}
$args=array(
‘tag__in’ => $tagIDs,
‘post__not_in’ => array($post->ID),
‘showposts’=>5,
‘caller_get_posts’=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<h3><a href=”/<?php the_permalink() ?>” rel=”bookmark” title=”<?php the_title(); ?>”><?php the_title(); ?></a></h3>
<?php endwhile;
} else { ?>
<h2>No related posts found!</h2>
<?php }
}
$post = $backup; // copy it back
wp_reset_query(); // to use the original query again
?>
13. Erase thousands of unfiltered spam comments in seconds
Often, spam comments survive the spam filters and reach your ‘awaiting moderation’ list. Deleting it manually could be time consuming. Follow the procedure to instantly delete thousands of such spam comments.
Log in to phpMyAdmin, select your WordPress database, click SQL and paste the code given below in the SQL command window.
DELETE from wp_comments WHERE comment_approved = ‘0’;
And now your WordPress site is:
14. Separate both comments and trackbacks
By default, WordPress combine both comments and trackbacks together. Separating both can make the things look more organized.
Step 1: Find the below code in the comments.php file.
<?php foreach ($comments as $comment) : ?>
Paste the below code after it.
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type == ‘comment’) { ?>
Step 2: Then, look for the below code
<?php endforeach; /* end for each comment */ ?>
Paste the below code before it
<?php } else { $trackback = true; } /* End of is_comment statement */ ?>
Step 3: Then, look for the following code
<?php else : // this is displayed if there are no comments so far ?>
Paste the below code before it
<?php if ($trackback == true) { ?>
<h3>Trackbacks</h3>
<ol>
<?php foreach ($comments as $comment) : ?>
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type != ‘comment’) { ?>
<li><?php comment_author_link() ?></li>
<?php } ?>
<?php endforeach; ?>
</ol>
<?php } ?>
15. Increase PHP memory
If you were activating a huge plugin and found an error that says memory exhausted just add the following line of code to your wp-config.php file.
define(‘WP_MEMORY_LIMIT’, ’64M’);
The above code will increase the memory limit to 64M.
16. Disable checking for plugin updates
WordPress automatically checks if plugins updates are available. The below trick comes in handy, in some cases such as if you worry that updating plugins might break your site. Paste the following code to your functions.php file and disable checking for plugin updates.
WARNING: Disabling plugin updates could lead to your WordPress website being compromised
remove_action( ‘load-update-core.php’, ‘wp_update_plugins’ );
add_filter( ‘pre_site_transient_update_plugins’, create_function( ‘$a’, “return null;” ) );
17. Increase maximum upload size through media uploader
Depending on the host, you’ll see a limit for the file size that you can upload through your Media uploader page in WordPress.
Add the below code to your .htaccess file to increase the upload limit to 64MB
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300
18. Redirect to a maintenance page
Sometimes you may need to redirect the site to a maintenance page. Create a maintenance page and name it as maintenance.html. Upload it to the root directory. Add the below code to .htacess and redirect all traffic to maintenance.html
# Redirect all traffic to maintenance.html file
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123
RewriteRule $ /maintenance.html [R=302,L]
19. Custom error pages
Create error pages for 403, 404 and 500 errors and upload it to your base WordPress installation. Then, add the following code snippet to your .htaccess file to enable the custom error pages.
# Custom error page for error 403, 404 and 500
ErrorDocument 404 /404-error.html
ErrorDocument 403 / 403-error.html
ErrorDocument 500 / 500-error.html
20. Highlight author comments in WordPress
To highlight the author comments, find the following code in your CSS file.
.bypostauthor { background: #eee; }
21. Stay logged in for a long(er) period
By default, WordPress keep you logged in for 2 weeks if you check the “remember me” option while logging in. Add the following code snippet to the functions.php file so you can stay logged in to your WordPress site for a year. You can convert any time to seconds and update accordingly if you want to be longer or shorter. We would suggest going for a month: 2629746 seconds
add_filter( ‘auth_cookie_expiration’, ‘stay_logged_in_for_1_year’ );
function stay_logged_in_for_1_year( $expire ) {
return 31556926; // 1 year in seconds
}
22. Change the footer text on WordPress dashboard
Add the following code to functions.php file to customize the footer text on the WordPress dashboard.
function remove_footer_admin () {
echo “Your own text”;
}
add_filter(‘admin_footer_text’, ‘remove_footer_admin’);
23. Enable shortcodes on widgets
By default, WordPress widgets aren’t enabled to manage shortcodes. Add the following code to functions.php file and empower your widgets to support shortcodes.
define(‘widget_text’, ‘do_shortcode’);
24. Change the length of excerpts
By default, length of the excerpts in WordPress is 55 words. Tweak the functions.php file by adding the following code to customize the length so it can fit the layout.
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( ‘excerpt_length’, ‘custom_excerpt_length’, 999 );
25. Display most commented posts
Add the following code to your theme’s functions.php file.
function wpb_most_commented_posts() {
ob_start();?>
<ul class=”most-commented”>
<?php
$query = new
WP_Query(‘orderby=comment_count&posts_per_page=10’);
while($query->have_posts()) : $query->the_post(); ?>
<li><a href=”/<?php the_permalink(); ?>” title=”<?php the_title(); ?>”><?php the_title(); ?></a> <span class=”wpb-comment-count”><?php comments_popup_link(‘No Comments;’, ‘1 Comment’, ‘% Comments’); ?></span></li>
<?php endwhile; ?>
</ul>
<?php// Turn off output buffering
$output = ob_get_clean();
return $output; }
add_shortcode(‘wpb_most_commented’, ‘wpb_most_commented_posts’);
add_filter(‘widget_text’, ‘do_shortcode’);
Then, add this shortcode in a widget wherever you want to display the most commented posts.
[wpb_most_commented]
26. Customize texts after the comment form
Add the following code to your theme’s functions.php file to customize the text before the comment form. Replace the ‘Your text here.’ with your preferred text.
function wpbeginner_comment_text_after($arg) {
$arg[‘comment_notes_after’] = “Your text here.”;
return $arg; }
add_filter(‘comment_form_defaults’, ‘wpbeginner_comment_text_after’);
27. Identify unused tags
If you delete old posts manually from MySQL, the tags you used on the posts will remain unused. Run the following SQL query to identify such unused tags.
SELECT * From wp_terms wt
INNER JOIN wp_term_taxonomy wtt ON wt.term_id=wtt.term_id WHERE wtt.taxonomy=’post_tag’ AND wtt.count=0;
28. Redirect mobile users to mobile site
This tricks comes in handy if you like to keeping a mobile version of your site to the responsive version. Add the following codes to .htaccess file to redirect the mobile users to mobile site.
RewriteEngine On
# Check for mime types commonly accepted by mobile devices
RewriteCond %{HTTP_ACCEPT} “text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml” [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^ http://m.domain.com%{REQUEST_URI} [R,L]
29. Remove help and screen options from dashboard
You can see the options “help” and “screen” on the top right hand side of your WordPress dashboard. Add the following code to functions.php for removing these options from the dashboard.
add_filter( ‘contextual_help’, ‘wpse_25034_remove_dashboard_help_tab’, 999, 3 );
add_filter( ‘screen_options_show_screen’, ‘wpse_25034_remove_help_tab’ );
function wpse_25034_remove_dashboard_help_tab( $old_help, $screen_id, $screen )
{
if( ‘dashboard’ != $screen->base )
return $old_help;
$screen->remove_help_tabs();
return $old_help;
}
function wpse_25034_remove_help_tab( $visible )
{
global $current_screen;
if( ‘dashboard’ == $current_screen->base )
return false;
return $visible;
}
30. Show popular posts in sidebar
To show 5 most popular posts according to the comments count, place the below code in 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>
31. Add breadcrumbs to the themes
For adding breadcrumbs, add the below code to your functions.php file.
function the_breadcrumb() {
echo ‘
<ul id=”crumbs”>’;
if (!is_home()) {
echo ‘
<li><a href=”‘;
echo get_option(‘home’);
echo ‘”>’;
bloginfo(‘name’);
echo “</a></li>
“;
if (is_category() || is_single()) {
echo ‘
<li>’;
the_category(‘title_li=’);
if (is_single()) {
echo “</li>
<li>”;
the_title();
echo ‘</li>
‘;
}
} elseif (is_page()) {
echo ‘
<li>’;
echo the_title();
echo ‘</li>
‘;
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo”
<li>Archive for “; the_time(‘F jS, Y’); echo'</li>
‘;}
elseif (is_month()) {echo”
<li>Archive for “; the_time(‘F, Y’); echo'</li>
‘;}
elseif (is_year()) {echo”
<li>Archive for “; the_time(‘Y’); echo'</li>
‘;}
elseif (is_author()) {echo”
<li>Author Archive”; echo'</li>
‘;}
elseif (isset($_GET[‘paged’]) && !empty($_GET[‘paged’])) {echo “
<li>Blog Archives”; echo'</li>
‘;}
elseif (is_search()) {echo”
<li>Search Results”; echo'</li>
‘;}
echo ‘</ul>
‘;
}
After that, add this line of code to your theme’s template where you would like the breadcrumbs to show up (for e.g. single.php, archives.php, etc.).
< ?php the_breadcrumb(); ?>
32. Customize your sidebar for individual posts
Display customized sidebar content for individual posts using custom fields. At first, find the following line of code in your single.php, index.php and page.php file.
<?php get_sidebar(); ?>
Replace it with the following code snippet.
<?php $sidebar = get_post_meta($post->ID, “sidebar”, true);
get_sidebar($sidebar);
?>
When writing a post, create new custom fields named sidebar. In the value section, mention the name of the sidebar you want to display so if you built two different sidebar files (for e.g. sidebar-category.php and sidebar-promotion.php) and wanted to show the sidebar-category.php, you’d use the key as “sidebar” and value as “sidebar-category“.
33. Define how individual posts should be displayed on the homepage
Most of the themes display all of your posts in the same way on the homepage. That is, on the homepage, either it shows excerpts only or it shows the full post. However, you may not want to display all of your posts in the same way in the homepage.
Find the loop in your index.php file and replace it with the following code so that you can define how each post should be displayed.
<?php if (have_posts()) :
while (have_posts()) : the_post();
$customField = get_post_custom_values(“full”);
if (isset($customField[0])) {
//Custom field is set, display a full post
the_title();
the_content();
} else {
// No custom field set, let’s display an excerpt
the_title();
the_excerpt();
endwhile;
endif;
?>
In this code, by default excerpts are displayed on the homepage. To show posts fully in the homepage, create a custom field ‘full’ from the post editor and give it any value.
34. Link to external links from your post titles
Usually, titles of blog posts in homepage are linked to the original post URL. However, if the sole purpose of publishing a particular blog post is to share a particular external link, you may not want to entice the users to open up your post. Instead, the users can visit the external link by simply clicking the blog post title from the homepage itself. Add the following code to functions.php file.
function print_post_title() {
global $post;
$thePostID = $post->ID;
$post_id = get_post($thePostID);
$title = $post_id->post_title;
$perm = get_permalink($post_id);
$post_keys = array(); $post_val = array();
$post_keys = get_post_custom_keys($thePostID);
if (!empty($post_keys)) {
foreach ($post_keys as $pkey) {
if ($pkey==’url1′ || $pkey==’title_url’ || $pkey==’url_title’) {
$post_val = get_post_custom_values($pkey);
}
}
if (empty($post_val)) {
$link = $perm;
} else {
$link = $post_val[0];
}
} else {
$link = $perm;
}
echo ‘<h2><a href=”‘.$link.'” rel=”bookmark” title=”‘.$title.'”>’.$title.'</a></h2>’;
}
Then, open your index.php and find the following code
<h2><a href=”/<?php the_permalink() ?>” rel=”bookmark”><?php the_title(); ?></a></h2>
Replace it with the below code and you’re done!
<h2><a href=”/<?php the_permalink() ?>” rel=”bookmark”><?php the_title(); ?></a></h2>
35. Add featured image support for your theme
‘Featured images’ is one of the most popular features of WordPress. It is supported in most of the themes available today. However, if your theme doesn’t support this feature, you can add following code to theme’s functions.php file
add_theme_support( ‘post-thumbnails’ );
36. Custom CSS for individual posts
You may need to use custom stylesheet for individual posts. Insert the following code in header.php between <head>and </head>
<?php if (is_single()) {
$customstyle = get_post_meta($post->ID, ‘customstyle’, true);
if (!empty($customstyle)) { ?>
<style type=”text/css”>
<?php echo $customstyle; ?>
<style>
<?php }
} ?>
Then, add a custom field in the posts with the name customstyle and add the CSS code in there.
37. Display most recent comments
Add the following code to anywhere on your theme where you want to display 5 most recent comments.
<?php
$query = “SELECT * from $wpdb->comments WHERE comment_approved= ‘1’
ORDER BY comment_date DESC LIMIT 0 ,5″;
$comments = $wpdb->get_results($query);
if ($comments) {
echo ‘<ul>’;
foreach ($comments as $comment) {
$url = ‘<a href=”‘. get_permalink($comment->comment_post_ID).’#comment-‘.$comment->comment_ID .'” title=”‘.$comment->comment_author .’ | ‘.get_the_title($comment->comment_post_ID).'”>’;
echo ‘<li>’;
echo ‘<div class=”img”>’;
echo $url;
echo get_avatar( $comment->comment_author_email, $img_w);
echo ‘</a></div>’;
echo ‘<div class=”txt”>Par: ‘;
echo $url;
echo $comment->comment_author;
echo ‘</a></div>’;
echo ‘</li>’;
}
echo ‘</ul>’;
}
?>
38. Add actionable buttons on published comments
Often, you might want to edit some published comments. By default, if you are logged in to your site, on top of every comment you published you can see a link where you can click to edit the comment. Additionally, how about marking a comment as spam or even delete it from your blog post itself?
Add the below code to functions.php file.
function delete_comment_link($id) {
if (current_user_can(‘edit_post’)) {
echo ‘| <a href=”‘.admin_url(“comment.php?action=cdc&c=$id”).'”>del</a> ‘;
echo ‘| <a href=”‘.admin_url(“comment.php?action=cdc&dt=spam&c=$id”).'”>spam</a>’;
}
}
Then, add the below code snippet to comments.php file.
delete_comment_link(get_comment_ID());
Wordpress Community tricks
The following WordPress tips tricks and tweaks are useful for multi author/community powered website.
39. Create custom user roles in WordPress
WordPress provides the following user roles by default- administrator, editor, author, contributor and subscriber. However, at times, you may need to assign some customized user roles.
For example, if you want to provide an option to edit the pages only to a new user, here’s how to do it.
Add the following code to functions.php file.
// Add a custom user role
$result = add_role( ‘new’, __(
‘New’ ),
array(
‘read’ => true, // true allows this capability
‘edit_posts’ => false, // Allows user to edit their own posts
‘edit_pages’ => true, // Allows user to edit pages
‘edit_others_posts’ => false, // Allows user to edit others posts not just their own
‘create_posts’ => false, // Allows user to create new posts
‘manage_categories’ => false, // Allows user to manage post categories
‘publish_posts’ => false, // Allows the user to publish, otherwise posts stays in draft mode
‘edit_themes’ => false, // false denies this capability. User can’t edit your theme
‘install_plugins’ => false, // User cant add new plugins
‘update_plugin’ => false, // User can’t update any plugins
‘update_core’ => false // user cant perform core updates
)
);
40. Disable admin bar except for admin
Often for membership/community site, the WordPress admin bar would not be customized for the end users. In such cases, you may want to disable admin bar access to other users except admin. Add the following code snippet to functions.php file to disable the access.
add_action(‘after_setup_theme’, ‘remove_admin_bar’);
function remove_admin_bar() {
if (!current_user_can(‘administrator’) && !is_admin()) {
show_admin_bar(false);
}
}
41. Disable admin bar access to all users
If you want to disable access to admin bar for all the users including the administrator, add the following code to functions.php file.
show_admin_bar(false);
42. Automatically add new users to BuddyPress group
This trick is for BuddyPress plugin, which is the most popular niche social network plugin for WordPress. By this tweak, you can automatically add all the newly joined BuddyPress members to a specific group.
function automatic_group_membership( $user_id ) {
if( !$user_id ) return false;
groups_accept_invite( $user_id, <# group ID #> );
}
add_action( ‘bp_core_activated_user’, ‘automatic_group_membership’ );
43. Add author bio wherever you want
Simply add the following code to single.php file to show author bio in your preferred location.
<div id=”author-bio”>
<h3>About <?php the_author(); ?></h3>
<?php echo get_avatar( get_the_author_email(), ’70’ ); ?>
<?php the_author_description(); ?>
</div>
In addition, add the following code to CSS file to make the author bio looks better
#author-bio { border-top: 1px dotted #cccccc; padding: 15px 0; }
#author-bio h3 { font-size: 16px; margin: 0 0 5px 0; }
#author-bio img { float: left; padding: 2px; border: 1px solid #cccccc; margin: 5px 15px 0 0; }
44. Replace “Howdy” message from the dashboard
Sometimes you may want to change the “Howdy” message from your WordPress dashboard and customize it according to your wish. Add the following code to functions.php file.
function replace_howdy( $wp_admin_bar ) {
$my_account=$wp_admin_bar->get_node(‘my-account’);
$newtitle = str_replace( ‘Howdy,’, ‘Logged in as’, $my_account->title );
$wp_admin_bar->add_node( array(
‘id’ => ‘my-account’,
‘title’ => $newtitle,
) );
}
add_filter( ‘admin_bar_menu’, ‘replace_howdy’,25 );
All that you needed is to insert the new message as the 2nd element within the $newtitle array, and you’re done.
45. Make featured image required for publishing a blog post
Tweak your functions.php file to make featured images mandatory for publishing blog posts.
add_action(‘save_post’, ‘wpds_check_thumbnail’);
add_action(‘admin_notices’, ‘wpds_thumbnail_error’);
function wpds_check_thumbnail( $post_id ) {
// change to any custom post type
if( get_post_type($post_id) != ‘post’ )
return;
if ( ! has_post_thumbnail( $post_id ) ) {
// set a transient to show the users an admin message
set_transient( “has_post_thumbnail”, “no” );
// unhook this function so it doesn’t loop infinitely
remove_action(‘save_post’, ‘wpds_check_thumbnail’);
// update the post set it to draft
wp_update_post(array(‘ID’ => $post_id, ‘post_status’ => ‘draft’));
add_action(‘save_post’, ‘wpds_check_thumbnail’);
} else {
delete_transient( “has_post_thumbnail” );
}
}
function wpds_thumbnail_error() {
// check if the transient is set, and display the error message
if ( get_transient( “has_post_thumbnail” ) == “no” ) {
echo “<div id=’message’ class=’error’><p><strong>You must add a Featured Image before publishing this. Don’t panic, your post is saved.</strong></p></div>”;
delete_transient( “has_post_thumbnail” );
}
}
46. Add confirmation box when publishing pages & posts
This trick avoids publishing an incomplete post by accident. You can add the following code to functions.php file.
add_action( ‘admin_print_footer_scripts’, ‘sr_publish_molly_guard’ );
function sr_publish_molly_guard() {
echo “
<script>
jQuery(document).ready(function($){
$(‘#publishing-action input[name=\”publish\”]’).click(function() {
if(confirm(‘Are you sure you want to publish this?’)) {
return true;
} else {
$(‘#publishing-action .spinner’).hide();
$(‘#publishing-action img’).hide();
$(this).removeClass(‘button-primary-disabled’);
return false;
}
});
});
</script>
“;
}
47. Redirect to custom page after registration
Paste the below snippet to functions.php file to redirect users to a custom page after registration
function __my_registration_redirect(){
return home_url( ‘/my-page’ );
}
add_filter( ‘registration_redirect’, ‘__my_registration_redirect’ );
48. Add social profile information on the user profile page
By default, the user profile page in the dashboard has fields to add the contact info including AIM, Yahoo IM, Jabber/Google Talk, etc. Open functions.php file and add the following code to add more social media fields in the user profile page.
function my_new_contactmethods( $contactmethods ) {
// Add Twitter
$contactmethods[‘twitter’] = ‘Twitter’;
//add Facebook
$contactmethods[‘facebook’] = ‘Facebook’;
return $contactmethods;
}
add_filter(‘user_contactmethods’,’my_new_contactmethods’,10,1);
You can use the following code in author.php file to display it.
echo $curauth->twitter;
49. List all authors of your blog in a page
Add the following code where you want to display the list of all authors of your blog.
<ul>
<?php wp_list_authors(‘exclude_admin=0&optioncount=1&show_fullname=1&hide_empty=1’); ?>
</ul>
50. Display guest author’s name via custom fields
Most guest authors are onetime publisher. So there is no point in creating a separate profile for them. Rather, add the following code to single.php where you’d like to display the author name.
<?php $author = get_post_meta($post->ID, “guest-author”, true);
if ($author != “”) {
echo $author;
} else {
the_author();
} ?>
Once done, create a custom field named guest-author and type your custom title as a value.
Wordpress Analytics Tricks
51. Insert Google Analytics code
Find the <body> tag inside the header.php file and insert the Google Analytics code right after.
52. A/B test using Google Analytics
A/B testing different versions of your page will help you improve the conversion rate. Here’s how to do A/B test on your WordPress site using Google Analytics.
1. Make sure you’ve installed Google Analytics on your WordPress site.
2. In your Google Analytics account, click the behavior tab>> click experiments>> choose your experiment objectives and configure your experiment.
Learn more about this step from the official site.
3. Find the page id of your original page, and replace $page_id with the id of your original page to the below code. Then, get the experiment code from Analytics and add it to the below code
<?php if (is_page($page_id)) :
?>
Add Content
Experiment Code Here
<?php endif; ?>
4. Save this code to header.php file and click next>>start experiment in Google Analytics.
53. Track file downloads using Google Analytics
Using Google Anlaytics’ event tracking functionality, you can track file downloads without a plugin. See the below example code for event tracking.
<a onclick=”_gaq.push([‘_trackEvent’,’Download’,’PDF’,this.href]);” href=”https://cdn.dart-creations.com/ebook.pdf” target=”_blank”>Download ebooks</a>
Monetization Tricks
WordPress tips tricks and tweaks for monetization of your website
Monetization is very important for most blogs, so why don’t you follow these recommendations for making some extra cash off your WP site.
54. Display AdSense ads only to search engines
If you look at the total ad clicks you receive on your website, you’ll find that search engines visitors are more likely to click the contextual ads like AdSense than any other visitor. So restricting your ad to display only to the visitors that come from search engine can help you increase the CTR of your ad.
To display ads only to search engine visitors, add the following code to your functions.php file.
$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) {
setcookie(“sevisitor”, 1, time()+3600, “/”, “.yourdomain.com”);
$sevisitor=true;
}
}
function visits_from_searchengine(){
global $sevisitor;
if ($sevisitor==true || $_COOKIE[“sevisitor”]==1) {
return true;
}
return false;
}
Make sure you change yourdomain.com to your domain. Then, add the following code snippet to single.php file.
<?php if (function_exists(‘visits_from_searchengine’)) {
if (visits_from_searchengine()) { ?>
YOUR CODE HERE
<?php } } ?>
Don’t forget to add your AdSense code by replacing YOUR CODE HERE.
55. Hide ads for single posts
If you are displaying advertisement on every blog post and want to hide ads for a certain post, just add the following code snippet to your single.php file. Make sure you replace xx with the post id and insert your ad code to below code snippet.
if(get_the_ID() != xx) {
Your ad code here
}
56. Embed ad inside the excerpts of first blog post
In homepage, you can place advertisement inside the excerpts of your first blog post.
Open index.php file and find <?php if (have_posts())
Add the following line above it:
<?php $count = 1; ?>
Then, find the code that starts with
<?php the_content
Add the following code after the closing tag, ?>
<?php if ($count == 1) : ?>
AD CODE
<?php endif; $count++; ?>
Make sure you replace AD CODE with your advertisement code.
57. Wrap ads in post wherever you want
In functions.php file, add the below code snippet. In addition, make sure you insert your ad codes inside it.
function googleadsense($content){
$adsensecode = ‘Your Ad Codes Here’;
$pattern = ‘<!-googlead->’;
$content = str_replace($pattern, $adsensecode, $content);
return $content;
}
add_filter(‘the_content’, ‘googleadsense’);
Insert <!-googlead-> in your posts and pages wherever you want to display the ad.
58. Export email addresses from user submitted comments
Execute the below SQL query against your database to export all the user submitted email addresses with no duplicates. This can be helpful for building your email list.
SELECT DISTINCT comment_author_email FROM wp_comments;
59. Display ads using shortcodes
Insert the shortcode, [adsense] anywhere inside the posts and pages content where you want the ads to be displayed. Just add the below given code to your functions.php file.
function showads() {
return ‘
ADS CODE HERE
‘;
}
add_shortcode(‘adsense‘, ‘showads‘);
60. Set expiration date for your posts
Setting expiration date for your post is a good idea especially if you are offering limited time discount for your products or running a contest.
Just replace the WordPress loop with the following code.
<?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;
?>
In the custom fields, make sure you choose key ‘expiration’ and the following date format: mm/dd/yyyy 00:00:00. This WordPress trick doesn’t remove or unpublish the post but it excludes the post from being displayed in the loop.
61. Add promotional content in homepage above the articles
In index.php file, find the following code: <div class=”content-loop”>. Add your promotional content above it, whether it is email newsletter form, advertisement, etc.
Wordpress Security Tricks
62. Limit access to log in page for specific ip addresses
If your ip addresses don’t change often, you can limit accessing to WordPress log in page to that specific IP address only.
See the following code, replace ‘one’ with your ip address and add the code to .htaccess file.
ErrorDocument 401 /path-to-your-site/index.php?error=404
ErrorDocument 403 /path-to-your-site/index.php?error=404
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$
RewriteCond %{REMOTE_ADDR} !^IP Address One$
RewriteRule ^(.*)$ – [R=403,L]
</IfModule>
63. Block specific ip address
Add the following code to .htaccess for denying certain ip addresses from accessing your site.
# allow all except those indicated here
<Files *>
order allow,deny
allow from all
deny from xxx.xxx.xxx.xxx
</Files>
64. Create a manual backup of your database
Log in to phpMyAdmin, select your WordPress database you want to backup. Click export, choose a compression method and click execute. When your browser prompts you to download the backup, click yes.
65. Use SSL mode for log in
If you have SSL certificate installed on your server, you can force your WordPress website to SSL mode for secure user log in.
For that, add the below code to wp-config.php file.
define(‘FORCE_SSL_LOGIN’, true);
66. Disable WordPress log error message
Tweak your functions.php by adding the following code snippet to disable WordPress log in error message.
function no_wordpress_errors(){
return ‘GET OFF MY LAWN !! RIGHT NOW !!’;
}
add_filter( ‘login_errors’, ‘no_wordpress_errors’ );
67. Restrict access to wp-includes file
Again, add the code to .htaccess file to disable the access to wp-includes.php
# Block wp-includes folder and files
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^wp-admin/includes/ – [F,L]
RewriteRule !^wp-includes/ – [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ – [F,L]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php – [F,L]
RewriteRule ^wp-includes/theme-compat/ – [F,L]
</IfModule>
68. Template file editing
Any WordPress user with administrator access can edit templates by navigating to Appearance > Editor.
You can disable template file editing by adding the following line of code to wp-config.php
define( ‘DISALLOW_FILE_EDIT’, true );
69. Hide WordPress version number
Each WordPress versions will have a few vulnerabilities. If a hacker manages to identify which version of WordPress you’re using, he can exploit it to gain control of your website through the known vulnerabilities.
Inserting below code to your functions.php will hide WP version number, which will be an added protection for your site.
remove_action(‘wp_head’,’wp_generator’);
70. Restore your WordPress database
Log in phpMyAdmin, select your WordPress database, click the import button, click browse and select the database you would like to restore from your hard disk. Then, click the execute button.
71. Disable access to directory
If you want to disable external access to the root directory, add the code to .htaccess file
# Disable directory browsing
Options All -Indexes
72. Disable access to specific file types
Create new .htaccess file, add the following code and upload the file inside wp-content folder.
# Disable access to all file types except the following
Order deny,allow
Deny from all
<Files ~ “.(xml|css|js|jpe?g|png|gif|pdf|docx|rtf|odf|zip|rar)$”>
Allow from all
</Files>
This will disable accessing all the file types except the mentioned files in the code.
73. Deny access to all .htaccess files
Add the code to .htaccess to deny access to all of your .htaccess files
# Deny access to all .htaccess files
<files ~ “^.*\.([Hh][Tt][Aa])”>
order allow,deny
deny from all
satisfy all
</files>
74. See recently modified files
If you have SSH access to your server, sign in and run the command below to see the recently modified files. This command comes in handy especially if you are suspecting vulnerable access to your server without your consent.
The below command will show changes made in last 2 days in the specified directory.
find /home/yourdirectory/yoursite/ –mtime -2 -ls
75. Manually reset your password
Log in to phpMyAdmin, select the WordPress database, click SQL and and paste the following command.
UPDATE `wp_users` SET `user_pass` = MD5(‘PASSWORD‘) WHERE `wp_users`.`user_login` =`admin` LIMIT 1;
Note: You need to change the ‘admin’ to your actual username and PASSWORD to your preferred password.
76. Deactivate all plugins when not able to access dashboard
Often, you may need to deactivate all plugins for troubleshooting. However, for some unfortunate reasons if you are not able to log in to your dashboard, you can deactivate all plugins from FTP.
Go to wp-content/ directory and change the folder name from plugins to something else.
77. Show all active plugins
For maintenance purposes, you might want to get the list of active plugins on a specific WordPress install. Paste the following code to functions.php file, and you’ll start seeing active plugins list on your dashboard.
add_action(‘wp_dashboard_setup’,’wpse_54742_wp_dashboard_setup’);
function wpse_54742_wp_dashboard_setup(){
wp_add_dashboard_widget(‘wpse_54742_active_site_plugins’, __(‘Active Plugins’),’wpse_54742_active_site_plugins’);} function wpse_54742_active_site_plugins(){
$the_plugs = get_option(‘active_plugins’);
echo ‘<ul>’;
foreach($the_plugs as $key => $value){
$string = explode(‘/’,$value);// Folder name will be displayed
echo ‘<li>’.$string[0].'</li>’; }
echo ‘</ul>’;}
78. Easily prevent comment spam
Instead of marking comments as spam each time, you can block the spammers outright from publishing comments on your blog. The below code will look for HTTP referrer and automatically blocks the comment if the referrer is not valid.
Add the below code in the functions.php file.
function check_referrer() {
if (!isset($_SERVER[‘HTTP_REFERER’]) || $_SERVER[