16 Useful Code Snippets for WordPress

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

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

function wps_registration_redirect(){
return home_url( ‘/finished/’ );
}
add_filter( ‘registration_redirect’, ‘wps_registration_redirect’ );

Sometimes you just want add shortcodes to a text widget. Luckily, this is a simple one line solution.

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

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.

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

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.

Automatic Linking to Twitter Usernames

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 anyways) – we’ve all experienced this at some point in time right?
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.

Adding Shortcodes to Widgets

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 exclude_category_home( $query ) {
if ( $query->is_home ) {
$query->set( ‘cat’, ‘-5, -34’ );
}
return $query;
} add_filter( ‘pre_get_posts’, ‘exclude_category_home’ );

Sure you can find plugins to meet just about every need imaginable but if you can find a simple snippet to get the job done, it’s usually the path of least resistance.

// Hide WordPress Update
function wp_hide_update() {
remove_action(‘admin_notices’, ‘update_nag’, 3);
}
add_action(‘admin_menu’,’wp_hide_update’);

Anytime you mention a company or individual from within a post it’s nice to link to their Twitter profile. This handy little snippet will watch your posts for text that signifies a Twitter username and then automatically create a link for you. Conveniently replacing no-link-@wpkube with @wpkube.

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

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

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.

Remove the Private/Protected From Your Post Titles

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

Show a Post Date and Modified Date

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

Remove the WordPress Version Number

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.

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 ". "; }
?>

add_filter( ‘widget_text’, ‘do_shortcode’ );

function year_shortcode() {
$year = date(‘Y’);
return $year;
}
add_shortcode(‘year’, ‘year_shortcode’);

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

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

Put an End to Automatic JPEG Compression

function remove_comment_fields($fields) {
unset($fields[‘url’]);
return $fields;
}
add_filter(‘comment_form_default_fields’,’remove_comment_fields’);

To get around this problem you’re left with a few choices:

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.
If your blog is continually the target of spammers, you can remove the URL field from comments which takes away most of their motivation.

Replace the “Howdy, User Name” With Anything You Desire

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

If you’re using a third-party image optimizer like Optimus or WP Smush, you might decide you want to disable the built-in WordPress image optimizer which is set to 90% out of the box.

Remove or Hide Categories From the Homepage

If you have a favorite WordPress snippet that you like to use please share it in the comments below.
Not everybody is a western fan. If that include 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:

Show X Results on the Search Results Page

function content_twitter_mention($content) {
return preg_replace(‘/([^a-zA-Z0-9-_&])@([0-9a-zA-Z_]+)/’, "@", $content);
}
add_filter(‘the_content’, ‘content_twitter_mention’);
add_filter(‘comment_text’, ‘content_twitter_mention’);

In case you want to hide your WordPress version number, from visitors just add this short snippet.

add_filter( ‘jpeg_quality’, ‘smashing_jpeg_quality’ );
function smashing_jpeg_quality() {
return 100;
}

Source: SmashingMagazine

Posted by WordPress Guru