WP-Mix

A fresh mix of code snippets and tutorials

18 Sweet WordPress Functions

Here is a collection of 18 sweet WordPress functions that can be used to improve the functionality of any WordPress-powered site. Enjoy!

Add custom styles to the Visual Editor

Spice up the default styles used by the Visual/Rich-Text Editor! Just add this snippet to your theme’s functions.php file:

// custom styles for visual editor
function shapeSpace_add_editor_styles() {
    add_editor_style('custom-editor-style.css');
}
add_action('admin_init', 'shapeSpace_add_editor_styles');

Remember to add the stylesheet, custom-editor-style.css to your theme directory, and then add some custom CSS to make it awesome.

Add theme support for Featured Images

Featured Images were originally referred to as “Post Thumbnails”, hence the tag name. Here is how to enable support for Featured Images in your theme:

function shapeSpace_add_post_thumbnails() {
	add_theme_support('post-thumbnails');
}
add_action('after_setup_theme', 'shapeSpace_add_post_thumbnails');

To set the default thumbnail size, add this line to the previous function:

set_post_thumbnail_size(200, 200, true);

This will set the default image size to 200px x 200px. You can change it to whatever is desired.

Add custom styles to the Login Page

This code snippet enables you to add some custom CSS to the login screen:

function shapeSpace_custom_login_styles() {
	echo '<link rel="stylesheet" type="text/css" media="all" href="'. get_stylesheet_directory_uri() .'/css/login.css">';
}
add_action('login_head', 'shapeSpace_custom_login_styles');

Don’t forget to add a stylesheet named login.css to your theme directory.

Add a widgetized sidebar

Give your theme a widgetized sidebar by adding the following code to your functions file:

function shapeSpace_widgets_init() {
	
	$widget_args_1 = array(
		
		'name'          => __('Widgets Header', 'shapespace'),
		'id'            => 'widgets_header',
		'class'         => '',
		'description'   => __('Widgets added here are displayed in the header', 'shapespace'),
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h2 class="widgettitle">',
		'after_title'   => '</h2>'
		
	);
	
	register_sidebar($widget_args_1);
	
}
add_action('widgets_init', 'shapeSpace_widgets_init');

Customize the parameters as desired to achieve the perfect configuration for your widget area.

Disable the Toolbar on the frontend

The Toolbar is great, but there are many scenarios where you don’t want it displayed on the front-end. This snippet does the job:

add_filter('show_admin_bar', '__return_false');

Trivia time! The Toolbar was original referred to as the Admin Bar

Customize the Admin footer text

This little snippet can be used to customize the text that is displayed in the footer of the WP Admin Area:

function shapeSpace_custom_admin_footer() {
	echo 'Theme developed by <a href="http://example.com/">Awesome People</a>';
}
add_filter('admin_footer_text', 'shapeSpace_custom_admin_footer');

Of course you’ll want to update the output text according to suit your own diabolical purposes.

Add Featured Images to feeds

By default your site’s RSS and other feeds do not include Featured Images. To include them, add the following code to your theme’s functions file:

function shapeSpace_feed_featured_image($content) {
	
	global $post;
	
	if (has_post_thumbnail($post->ID)) {
		$content = get_the_post_thumbnail($post->ID, 'thumbnail') . $content;
	}
	
	return $content;
	
}
add_filter('the_excerpt_rss',  'shapeSpace_feed_featured_image');
add_filter('the_content_feed', 'shapeSpace_feed_featured_image');

You can customize the Featured Image via get_the_post_thumbnail().

Add a navigation menu

Go big or go home! This function enables you to add a custom navigation menu to your theme:

function shapeSpace_setup() {

	register_nav_menus(array(
		'menu-header'  => __('Header Menu',  'shapespace'),
		'menu-sidebar' => __('Sidebar Menu', 'shapespace'),
		'menu-footer'  => __('Footer Menu',  'shapespace')
	));

}
add_action('after_setup_theme', 'shapeSpace_setup');

Note that this function name is used elsewhere in this WP-Mix post. So instead of including both in your theme, simply combine their contents into a single shapeSpace_setup() function. Yeah, you get it.

Custom styles for the entire Admin Area

We’ve seen how to add custom styles to the WP Login Page; here’s a code snippet that enables you to customize the entire Admin Area:

function shapeSpace_custom_admin_area() {
	echo '<link rel="stylesheet" type="text/css" href="'. get_stylesheet_directory_uri() .'/css/admin.css"/>';
}
add_action('admin_head', 'shapeSpace_custom_admin_area');

Remember to add the file, admin.css, to your theme directory, then style as desired to make it all so great.

Add default content to the Edit screen

Instead of staring at an empty field on the Edit Post screen, add the following code to help kick-start your writing efforts:

function shapeSpace_default_post_text($content) {
	
	global $post_type;
	
	if ($post_type === 'post') {
		
		$array = array(
			'Random bit of motivation',
			'Another random quotation',
			'Customize these as desired',
		);
		
	} else { // other post types
		
		$array = array(
			'Random bit of motivation',
			'Another random quotation',
			'Customize these as desired',
		);
		
	}
	
	return $array[array_rand($array)];
	
}
add_filter('default_content', 'shapeSpace_default_post_text');

Change the array values to whatever pumps you up; they will be displayed randomly each time you visit the Edit screen.

Customize number of search results

By default, the number of displayed search results is the same as the displayed number of posts (as set via your site’s Reading options). But sometimes, you want to display a different number of search results. Add this code to your theme’s functions.php to make it happen:

function shapeSpace_search_results_per_page($query) {
	
	global $wp_the_query;
	
	if (!is_admin() && $query->is_main_query()) {
		if ($query->is_search) {
			$query->set('posts_per_page', 50);
		}
	}
	
	return $query;
	
}
add_action('pre_get_posts', 'shapeSpace_search_results_per_page');

Here we are setting the number of search results per page to 50; feel free to customize that however is required. Also check this out.

Add a custom “Read More” link

This snippet adds a custom “read more” link after each post excerpt:

function shapeSpace_custom_read_more($content) {
	
	return str_replace('[...]',
		'<a class="read-more" href="'. get_permalink() .'">Continue Reading</a>',
		$content
	);
	
}
add_filter('the_excerpt', 'shapeSpace_custom_read_more');

Technically this function is replacing the default [...] with an actual link to the post. Way more useful than an ellipsis ;)

Custom classes for the body tag

There are a million ways to customize the output of body_class(). Here is an example that shows how to add a class of has-sidebar if a sidebar is present:

function shapeSpace_custom_body_class($classes) {
	
	if (is_active_sidebar('sidebar')) {
		$classes[] = 'has-sidebar';
	}
	
	return $classes;
	
}
add_filter('body_class', 'shapeSpace_custom_body_class');

Related: WordPress Random Post Class »

Create custom image sizes

When uploading images via the WP Media Library, you may want to generate some of your own custom sizes. Here is an example of how to do it:

function shapeSpace_setup_images() {
	
	// thumb size for wide layout: post-thumbnail-narrow
	add_image_size('post-thumbnail-narrow', '900', '600', array('center', 'center')); // crop from center
	
	// thumb size for wide layout: post-thumbnail-wide
	add_image_size('post-thumbnail-wide', '1840', '600', array('center', 'center')); // crop from center
	
}
add_action('after_setup_theme', 'shapeSpace_setup_images');

Here we are adding two custom image sizes: post-thumbnail-narrow and post-thumbnail-wide. You can then access these sizes via your theme template like so:

the_post_thumbnail('post-thumbnail-narrow');
the_post_thumbnail('post-thumbnail-wide');

..or:

get_the_post_thumbnail($post_id, 'post-thumbnail-narrow');
get_the_post_thumbnail($post_id, 'post-thumbnail-wide');

Remove paragraph tags around images

By default WordPress wraps images with <p> tags. This normally is fine, but there are scenarios where it may be undesirable. To make it stop, add the following function to your theme’s functions.php file:

function shapeSpace_no_ptags_around_img($content){
	return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
add_filter('the_content', 'shapeSpace_no_ptags_around_img');

Finally, no more wrapping images with paragraph tags!

Custom styles for old versions of IE

Older versions of Internet Explorer may display your theme design in some unexpected ways. To help correct anything weird, WordPress makes it easy to identify the IE browser, and then we can use conditional comments to target specific versions:

function shapeSpace_target_old_ie() {
	
	global $is_IE;
	
	if ($is_IE) {
		echo '<!--[if lt IE 9]><style>body { background-color: red; }</style><![endif]-->';
	}
	
}
add_action('wp_head', 'shapeSpace_target_old_ie');

Here we are adding a background color to all versions of IE less than 9. Note that you can add any markup within the conditional comments.

Security boost: obscure login errors

Instead of revealing potentially sensitive information when someone enters incorrect login credentials, you can obscure the error message:

function shapeSpace_obscure_login_errors() {
	return 'Sorry little dude, please try again!';
}
add_filter('login_errors', 'shapeSpace_obscure_login_errors');

You can change the message to whatever you want, have some fun (but don’t forget about usability).

Security boost: disable file editing

By default, WordPress enables administrators to edit files within the WP Admin Area. That’s fine if your site’s admins are all 100% legit, but if there are any doubts, you can disable the file-editing functionality by adding the following code to your site’s wp-config.php file:

define('DISALLOW_FILE_EDIT', true); // disable theme/plugin file editing

That’s all folks! I hope you benefit from these sweet WordPress functions :)

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress