We know that plugins can be used to extend the functionality of WordPress. But what if you can do some smaller things in WordPress without installing them? Say, you dislike the admin bar at the top and wish to eliminate it? Yes, that can be accomplished by means of code snippets for WordPress.
Basically, code snippets for WordPress are used to do certain actions that might otherwise require a dedicated smaller plugin. Furthermore, such code snippets are placed in one of the WordPress core or theme files (generally the functions.php file of your theme).
In this article, we have listed some very useful code snippets for WordPress users:
WORD OF CAUTION!
As you might have guessed, code snippets for WordPress, while really useful, tend to alter the default functionality. There can be a small margin of error with each snippet. Generally, such issues tend to arise due to incompatible plugins and/or themes and tend to disappear once you eliminate the said theme/plugin or decide not to use the said snippet.
However, to be on the safer side, be very sure to take proper backups of your WordPress website before making any changes by means of snippets. Also, if you encounter any error or performance issues, rollback your site and check for any plugins or incompatible theme issues.
Now, on to the code snippets for WordPress users!
1. ALLOW CONTRIBUTORS TO UPLOAD IMAGES
By default, WordPress does not permit contributor accounts to upload images. You can, of course, promote that particular account to Author or Editor and this will give them the rights to upload and modify images, However, it will also grant them additional rights, such as the ability to publish their own articles (as opposed to submission for review).
This particular code snippet allows contributor accounts to upload images to their articles, without granting them any additional privileges or rights. Paste it in the functions.php file of your theme:
if ( current_user_can('contributor') && !current_user_can('upload_files') )
add_action('admin_init', 'allow_contributor_uploads');
function allow_contributor_uploads() {
$contributor = get_role('contributor');
$contributor->add_cap('upload_files');
}
2. SHOW POPULAR POSTS WITHOUT PLUGINS
This one is a little trickier. However, if you are not too keen on installing an extra plugin to showcase popular posts (say, you have limited server memory or disk space), follow this snippet.
Paste the following in functions.php:
function count_post_visits() {
if( is_single() ) {
global $post;
$views = get_post_meta( $post->ID, 'my_post_viewed', true );
if( $views == '' ) {
update_post_meta( $post->ID, 'my_post_viewed', '1' );
} else {
$views_no = intval( $views );
update_post_meta( $post->ID, 'my_post_viewed', ++$views_no );
}
}
}
add_action( 'wp_head', 'count_post_visits' );
Thereafter, paste the following wherever in your template files that you wish to display the popular posts:
$popular_posts_args = array(
'posts_per_page' => 3,
'meta_key' => 'my_post_viewed',
'orderby' => 'meta_value_num',
'order'=> 'DESC'
);
$popular_posts_loop = new WP_Query( $popular_posts_args );
while( $popular_posts_loop->have_posts() ):
$popular_posts_loop->the_post();
// Loop continues
endwhile;
wp_reset_query();
3. DISABLE SEARCH IN WORDPRESS
The search feature of WordPress has been around for a long time. However, if your website does not need it, or you do not want users to “search” through your website for some reason, you can use this code snippet.
Essentially, it is a custom function that simply nullifies the search feature. Not just the search bar in your sidebar or the menu, but the entire concept of native WP search is gone. Why can this be useful? Again, it can help if you are running your website on low spec server and do not have content that needs to be searched (probably you aren’t running a blog).
Again, add this to the functions.php file:
function fb_filter_query( $query, $error = true ) {
if ( is_search() ) {
$query->is_search = false;
$query->query_vars[s] = false;
$query->query[s] = false;
// to error
if ( $error == true )
$query->is_404 = true;
}
}
add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );
4. PROTECT YOUR SITE FROM MALICIOUS REQUESTS
There are various ways to secure your website. You can install a security plugin, turn on a firewall or opt for a free feature such as Jetpack Protect that blocks brute force attacks on your website.
The following code snippet, once placed in your functions.php file, rejects all malicious URL requests:
global $user_ID; if($user_ID) {
if(!current_user_can('administrator')) {
if (strlen($_SERVER['REQUEST_URI']) > 255 ||
stripos($_SERVER['REQUEST_URI'], "eval(") ||
stripos($_SERVER['REQUEST_URI'], "CONCAT") ||
stripos($_SERVER['REQUEST_URI'], "UNION+SELECT") ||
stripos($_SERVER['REQUEST_URI'], "base64")) {
@header("HTTP/1.1 414 Request-URI Too Long");
@header("Status: 414 Request-URI Too Long");
@header("Connection: Close");
@exit;
}
}
}
5. PAGINATE YOUR SITE WITHOUT PLUGINS
Good pagination is very useful for allowing users to browse through your website. Rather than “previous” or “next” links. This is where another one of our code snippets for WordPress comes into play – it adds good pagination to your content.
In functions.php:
global $wp_query;
$total = $wp_query->max_num_pages;
// only bother with the rest if we have more than 1 page!
if ( $total > 1 ) {
// get the current page
if ( !$current_page = get_query_var('paged') )
$current_page = 1;
// structure of "format" depends on whether we're using pretty permalinks
$format = empty( get_option('permalink_structure') ) ? '&page=%#%' : 'page/%#%/';
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => $format,
'current' => $current_page,
'total' => $total,
'mid_size' => 4,
'type' => 'list'
));
}
6. DISABLE THE ADMIN BAR
The WordPress Admin Bar provides handy links to several key functions such as the ability to add new posts and pages, etc. However, if you find no use for it and wish to remove it, simply paste the following code snippet to your functions.php file:
// Remove the admin bar from the front end
add_filter( 'show_admin_bar', '__return_false' );
7. SHOW POST THUMBNAILS IN RSS FEED
If you wish to show post thumbnail images in your blog’s RSS feed, the following code snippet for WordPress can be useful.
Place it in your functions.php file:
// Put post thumbnails into rss feed
function wpfme_feed_post_thumbnail($content) {
global $post;
if(has_post_thumbnail($post->ID)) {
$content = '' . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'wpfme_feed_post_thumbnail');
add_filter('the_content_feed', 'wpfme_feed_post_thumbnail');
8. CHANGE THE AUTHOR PERMALINK STRUCTURE
By default, WordPress shows author profiles as yoursite.com/author/name
. However, you can change it to anything that you like, such as yoursite.com/writer/name
The following code snippet needs to be pasted in the functions.php file. Then, it changes the author permalink structure to “/profile/name”:
add_action('init', 'cng_author_base');
function cng_author_base() {
global $wp_rewrite;
$author_slug = 'profile'; // change slug name
$wp_rewrite->author_base = $author_slug;
}
9. AUTOMATICALLY LINK TO TWITTER USERNAMES IN CONTENT
This is especially useful if you are running a website that focuses a lot on Twitter (probably a viral content site, etc.) The following code snippet for functions.php converts all @ mentions in your content to their respective Twitter profiles.
For example, an @happy mention in your content will be converted to a link to the Twitter account “twitter.com/happy” (“happy” being the username):
function content_twitter_mention($content) {
return preg_replace('/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/', "$1<a href=\"http://twitter.com/$2\" target=\"_blank\" rel=\"nofollow\">@$2</a>", $content);
}
add_filter('the_content', 'content_twitter_mention');
add_filter('comment_text', 'content_twitter_mention');
10. CREATE A PAYPAL DONATION SHORTCODE
If you are using the PayPal Donate function to accept donations from your website’s visitors, you can use this code snippet to create a shortcode, and thus make donating easier. First, paste the following in your functions.php file:
function donate_shortcode( $atts, $content = null) {
global $post;extract(shortcode_atts(array(
'account' => 'your-paypal-email-address',
'for' => $post->post_title,
'onHover' => '',
), $atts));
if(empty($content)) $content='Make A Donation';
return '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation for '.$for.'" title="'.$onHover.'">'.$content.'</a>';
}
add_shortcode('donate', 'donate_shortcode');
Then, you can easily use the [donate] shortcode, such as:
[donate]My Text Here[/donate]