It’s the little things that make a difference, right? That’s part of what makes WordPress so great – the number of ways in which it can be customized to meet your specific needs is virtually limitless.
So I have gathered my own Additional Useful Code Snippets for WordPress.
Sure you can find plugins to meet just about every need imaginable which usually cost you your load time on the website. What if you can find a simple snippet to get the job done, it’s usually the path of least resistance.
We’ve put together a collection of useful snippets from around the web, all of which can make your life with WordPress just a little bit easier and more functional.
Using Code Snippets for WordPress
There are a few different ways to use code snippets. Most of the time, you’ll find yourself heading to the functions.php file but give that some extra thought.
Your functions.php file is very specific to your theme. If you decide to change themes down the road and have functions that are non-theme specific, you’ll have to start from scratch. Also, if you make changes to your parent theme and then update, all your changes will be overwritten. Make sure you’re using a child theme.
To get around this problem you’re left with a few choices:
- Write a custom plugin. (Stay tune – coming soon how to make your custom plugins using code snippets)
- A snippet plugin like Code Snippets.
- A theme specific plugin.
- A child theme and put all function changes in the child theme.
A free plugin like code-snippets will allow you to create your own customized repository of snippets that can be activated or deactivated as required without having to mess around with your functions.php file.
There are other solutions as well, for example, if you’re running a Genesis theme, you could use the Genesis Extender Plugin from Cobalt Apps which allows you to add custom Functions through the plugin back-end. This particular plugin also lets you stop the custom functions from affecting the WordPress admin area. This can prevent breaking your entire site (at least the back-end anyway) – we’ve all experienced this at some point in time, right?
The final piece of advice, before we jump into the good stuff, is to always back up your site before you start making changes – especially make sure you have a copy of your original functions.php file handy.
You can try our agency techinfinity.io for any technical guidance and help in fixing any bugs or errors you have or comment below to get in touch with us.
Adding Shortcodes to Widgets
Sometimes you just want to add shortcodes to a text widget. Luckily, this is a simple one-line solution.
add_filter( 'widget_text', 'do_shortcode' );
Redirect New Registered Users to a Specific Page
If you require a new user to register on your WordPress site, you might want to redirect them to a specific page upon successful completion. Maybe you want to provide them with some important information or a specific download.
function wps_registration_redirect(){
return home_url( '/finished/' );
}
add_filter( 'registration_redirect', 'wps_registration_redirect' );
Limiting WordPress Post Revisions
Keeping track of post revisions in WordPress is a great feature – to a certain extent. If you do much editing within the WordPress editor it’s easy to end up with dozens or even hundreds of revisions stored in the database. An easy fix is to limit the number of revisions per post to something more reasonable like 3-5.
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', 5);
if (!defined('WP_POST_REVISIONS')) define('WP_POST_REVISIONS', false);
Using the Current Year in Your Posts
Do you ever wish you could insert the current year in some of your posts via a simple shortcode?
Add the snippet below to your functions.php file and you’ll be partying like it’s [year].
function year_shortcode() {
$year = date('Y');
return $year;
}
add_shortcode('year', 'year_shortcode');
Remove the Private/Protected From Your Post Titles
In case you ever publish posts that are private, you’ll notice that the title is prefaced by an unsightly reminder. You can add the code below to your functions file and everything will look good again.
function the_title_trim($title) {
$title = attribute_escape($title);
$findthese = array(
'#Protected:#',
'#Private:#'
);
$replacewith = array(
'', // What to replace "Protected:" with
'' // What to replace "Private:" with
);
$title = preg_replace($findthese, $replacewith, $title);
return $title;
}
add_filter('the_title', 'the_title_trim');
Show a Post Date and Modified Date
Sometimes six months after you write a post you decide to update it with some new information. This simple snippet will add a modified date to your posts in the event that you make a change sometime after the initial publication date. This usually happens to me I start a blog post but never complete it so it’s a handy modification for my website to get the latest modified date also it gives google a signal of the latest modified which increases your chance to get featured on Google Display News.
Posted on <?php the_time('F jS, Y') ?>
<?php
$u_time = get_the_time('U');
$u_modified_time = get_the_modified_time('U');
if ($u_modified_time != $u_time) {
echo "and last modified on ";
the_modified_time('F jS, Y');
echo ". ";
}
?
Remove the WordPress Version Number
In case you want to hide your WordPress version number, from visitors just add this short snippet.
<?php
// Remove the version number of WP
// Warning - this info is also available in the readme.html file in your root directory - delete this file!
remove_action('wp_head', 'wp_generator');
>
Hide the WordPress Update Message
When managing client websites, sometimes you want to delay updating to the latest version of WordPress until you’ve had a chance to create a new backup. This snippet will hide the tempting update message that shows up in the header.
// Hide WordPress Update
function wp_hide_update() {
remove_action('admin_notices', 'update_nag', 3);
}
add_action('admin_menu','wp_hide_update');
Remove the Comment URL Field
If your blog is continually the target of spammers, you can remove the URL field from comments which takes away most of their motivation.
As the comment field URL is a DoFollow Lik which gives spammer to attack on comments so they get a backlink.
function remove_comment_fields($fields) {
unset($fields['url']);
return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');
Wondering How Many Images an Author Has Attached to a Post?
When authors are responsible for adding their own images to a post, it’s nice to know-how may have been attached with a quick glance. This snippet adds a custom admin column.
add_filter('manage_posts_columns', 'posts_columns_attachment_count', 5);
add_action('manage_posts_custom_column', 'posts_custom_columns_attachment_count', 5, 2);
function posts_columns_attachment_count($defaults)
{
$defaults['wps_post_attachments'] = __('Attached');
return $defaults;
}
function posts_custom_columns_attachment_count($column_name, $id)
{
if($column_name === 'wps_post_attachments')
{
$attachments = get_children(array('post_parent'=>$id));
$count = count($attachments);
if($count !=0){echo $count;}
}
}
Put an End to Automatic JPEG Compression
If you’re using a third-party image optimizer like Optimus or WP Smush which I do, you might decide you want to disable the built-in WordPress image optimizer which is set to 90% out of the box.
add_filter( 'jpeg_quality', 'smashing_jpeg_quality' );
function smashing_jpeg_quality() {
return 100;
}
Require a Featured Image
This is a great idea if you have clients who are creating their own posts. After you spend time devising an attractive template layout, clients often decide to skip the featured image, ruining the flow and presentation of what you’ve created. This snippet will require the author to select a featured image before the post can be published.
I usually forget to add a featured image while publishing a post so this comes in handy for my website to keep me restricted on publishing post without a featured image.
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">
You must select Featured Image. Your Post is saved but it can not be published.
</div>
";
delete_transient( "has_post_thumbnail" );
}
}
Replace the “Howdy, User Name” With Anything You Desire
Not everybody is a western fan definitely I am not one of them. If that includes you, maybe it’s time to change the “Howdy” message that appears in the header for logged-in users. Something more appropriate might be in order such as “You’re being watched”. Maybe that’s a little creepy – perhaps a simple “Welcome” or a “Logged in as” would be more appropriate. Add the code below to your functions.php:
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 );
Remove or Hide Categories From the Homepage
Sometimes you want to remove or avoid displaying certain categories on your home page. Some premium themes have this function built-in so be sure to check your theme settings first. Failing that this little snippet should do the trick.
function exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( 'cat', '-5, -34' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category_home' );
Show X Results on the Search Results Page
If you want to change the default number of search results returned to something greater or less that the default this snippet will let you do just that.
function limit_posts_per_search_page() {
if ( is_search() )
set_query_var('posts_per_archive_page', 20);
}
add_filter('pre_get_posts', 'limit_posts_per_search_page');
If you have a favorite WordPress snippet that you like to use please share it in the comments below.
Also Read: WordPress Easy Guide on Code Snippets and don’t forget 10 Useful Code Snippets for every WordPress Users