Archive for WordPress

Clients are Scared of the Childish Blog?

wordpress-logo-hoz-rgb

They are out there. Clients who believe blogs are childish things similar to a corporate presence being established on MySpace. You, the developer, want to build them an incredible website powered by WordPress. But when they see the backend and these things called posts, they refuse to pay because you built them a childish website not fit for the corporate world. (Trust me, I know of someone this happened to.) Well, this can all be fixed by created a little filter to your active theme's functions.php file.

function turn_post_into_article($translated){
	$translated = str_ireplace('Post', 'Article', $translated);
	return $translated;
}
add_filter('gettext', 'turn_post_into_article');
add_filter('ngettext', 'turn_post_into_article');

This simple code will rename (or translate) the word Post into Article throughout your website. Now you don't have to worry about your clients getting worried that you built them a childish site with posts. :)

Set Maximum Post Title Length

wordpress-logo-hoz-rgb

You might have developed the perfect custom theme for a client. Everything looks perfect and because you're using WordPress it is very easy for the client to update the site. But then one day you take a look at the site and something went wrong... because the client just wrote a post with a title that looks like this:

The Perfect Way to Create a Core Web Application Development with PHP and MySQL while Managing Complex User Equations that are Maximized by the Global Time Exchange Pass-Loss during the Communicative Process of Client-Server Ghosting

So... the title is WAY TOO LONG... and it breaks the mold of the site that you spent hours crafting. This little code snippet will set a maximum amount of words allowed in the Post Title field. In the example code below, we have set the maximum number of words in the Post Title to 10. If there are more than 10 words, we will return an error message telling the client to shorten their title. This code goes in your active theme's functions.php file.

function maxTitleLength($title) {
  global $post;
  $title = $post->post_title;
  if (str_word_count($title) >= 10)
    wp_die( __('Error: your post title is over the maximum word count.'));
}
add_action('publish_post','maxTitleLength');

Force WordPress Admin to use SSL

wordpress-logo-hoz-rgb

A helpful security tip when using WordPress is to force your WordPress Admin Dashboard to use Secure Socket Layer (SSL). Remember that you need to already have SSL setup on your domain. This code goes in your wp-config.php file and will force your Admin Dashboard to use https:// instead of http://.

define('FORCE_SSL_ADMIN', true);

Changing the WordPress Read More Text

wordpress-logo-hoz-rgb

WordPress has a built-in ability to split a post or block of content into two parts. This is traditionally used to only show a portion or excerpt of the post on the front page of a blog, and then the reader can click on a link to read the full version of the post/content. Out-of-the-box the text of the link that readers click on to view the full version of the post says Read More. If you want to change the text all you have to do is add the following code to your active theme's functions.php file.

$custom_morelink = "Continue Reading the Full Article";
function change_more_link($more_link, $more_link_text) {
  return str_replace($more_link_text, $custom_morelink, $more_link);
}
add_filter('the_content_more_link', 'change_more_link', 10, 2);

Make sure you replace the text Continue Reading the Full Article with your own text that you want to appear instead of the standard Read More.

Update: Forgot to mention a simple way to change just one Read More text link. For example: you can use the above PHP code to change every single Read More text, but you can also just use a simple method to change the text directly in the WordPress more tag.

< !--more Continue Reading the Full Article-->

And just in case you forgot what the standard/default WordPress more tag looks like...

< !--more-->

So you see, by simply adding the text you want to appear (instead of the Read More text) inside the more tag, you have extra control over the look of your site.

Add Menu Items to Admin Toolbar

wordpress-logo-hoz-rgb

One of the easiest ways to brand WordPress when doing client work is to add your web design business to the WordPress Admin Toolbar. Adding links and menu items to the WordPress Admin Toolbar is easily done through a simple add_action WordPress hook. In this example, we are adding a link to a fictitious webdev studio, as well as drop-down links to the Support, Billing, and News Updates of said fictitious webdev studio.

This code can be placed in the active theme's functions.php file.

function easy_add_menu_items_to_toolbar() {
  global $wp_admin_bar;
  if (!is_super_admin() || !is_admin_bar_showing())
    return;
  $wp_admin_bar->add_menu(array(
    'id' => 'webdev_links',
    'title' => __('Awesome WebDev'),
    'href' => __('http://domain.com'),
  ));
  $wp_admin_bar->add_menu(array(
    'parent' => 'webdev_links',
    'id' => 'support',
    'title' => __('Get Support'),
    'href' => __('http://domain.com/support'),
  ));
  $wp_admin_bar->add_menu(array(
    'parent' => 'webdev_links',
    'id' => 'billing',
    'title' => __('Pay Your Bill'),
    'href' => __('http://domain.com/billing'),
  ));
  $wp_admin_bar->add_menu(array(
    'parent' => 'webdev_links',
    'id' => 'news',
    'title' => __('Latest News'),
    'href' => __('http://domain.com/news'),
  ));
}
add_action('admin_bar_menu', 'easy_add_menu_items_to_toolbar', 25);

As you can see, each time we add_menu to the $wp_admin_bar we setup an array. Inside the array we have four different options.

  • 'parent' - This is how we create a drop down menu. If you want a menu item to have a parent, you place the parent's 'id' inside your array.
  • 'id' - This is the unique name for each menu item.
  • 'title' - This is the text that appears to the end-user on the Toolbar menu item.
  • 'href' - This is the url location of where you want the user to go when they select the menu item.

If you wanted to take it a step further, you could also assign CSS classes to individual menu items... which would be a great way to integrate icons/graphics into your WordPress Admin Toolbar. The following code will assign a CSS class of super-css-class to this newly added specific WordPress Admin Toolbar menu item.

$wp_admin_bar->add_menu(array(
  'id' => 'super_css',
  'title' => __('Super CSS'),
  'href' => __('http://domain.com/supercss'),
  'meta' => array(
    'class' => 'super-css-class',
  ),
));

Bonus Content: You can also use this exact same code to remove items from the default WordPress Admin Toolbar. I prefer to create a different function when removing items. This way the adding of content happens in one function and the removing of content happens in another function.

function remove_admin_toolbar_links() {
  global $wp_admin_bar;
  $wp_admin_bar->remove_menu('wp-logo');
  $wp_admin_bar->remove_menu('updates');
}
add_action('wp_before_admin_bar_render', 'remove_admin_toolbar_links');

The above code removes the WordPress logo from the Admin Toolbar and also the section that shows there are updates to WordPress (great to remove from clients). You can remove everything if you want and simply recreate the WordPress Admin Toolbar into a completely different beast. If you want to go down that road, here are the names of the sections you might want to remove.

  • wp-logo - the WordPress logo
  • my-account - links to your account. The ID depends upon if you have avatar enabled or not.
  • site-name - site name with other dashboard items
  • my-sites - the My Sites menu (if you have more than one site, multisite)
  • get_shortlink - shortlink to the post/page
  • edit - Post/Page/Category/Tag edit link
  • new-content - Add New menu
  • comments - Comments menu
  • updates - Updates menu
  • search - Search box

Are you currently modifying the WordPress Admin Toolbar for yourself or your clients?

Add a Search Box to WordPress Navigation

wordpress-logo-hoz-rgb

You've all seen sites that have a built-in search box as part of a navigation bar. With WordPress, it is really easy to do. All we have to do is add a search form to the list of navigational items through a filter. This code would go into your active theme's functions.php file. Caution: You will need to replace the INSERT-YOUR-MENU text with the actual name of your custom menu you create in WordPress.

function add_search_form($items, $args) {
if( $args->theme_location == 'MENU-NAME' )
        $items .= '<li class="search"><form role="search" method="get" id="searchform" action="'.home_url( '/' ).'"><input type="text" value="search" name="s" id="s" /><input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /></form></li>';
        return $items;
}
add_filter('wp_nav_menu_items', 'add_search_form', 10, 2);

There really are a number of ways to do this, but with this code it doesn't matter what theme you are using, it will simply filter in a search form as an additional menu item in the navigational menu list.

Resizing the WordPress Excerpt Box

wordpress-logo-hoz-rgb

This is a regular occurrence. You or your client are using a theme that takes advantage of the excerpt box in the WordPress post editor to display unique content in different locations of the theme. But each time you go to the WordPress editor page you always have to adjust the size of the excerpt meta box because its always too small. If this is something that has happened to you... there is an easy fix. This code goes in your active theme's functions.php file and will automatically adjust the size of the excerpt meta box for you.

function excerpt_textarea_height() {
    echo'
    <style type="text/css">
        #excerpt{ height:500px; }
    </style>
    ';
}
add_action('admin_head', 'excerpt_textarea_height');

Stop WordPress from Compressing JPGs

Did you know that WordPress compresses your jpg files? Well, if you down want any loss of quality of your images... especially if you are sharing some photographs, add this line of code to your active theme's functions.php file.

add_filter('jpeg_quality', function($arg){return 100;});

Now the jpg files you upload will be the exact file you upload, not some compressed version.

Do you forget to set your featured image in WordPress?

wordpress-logo-hoz-rgb

If you are anything like me or have a client who is like me, this code will help you tremendously. If you ever forget to set a the featured image (post thumbnail) in your WordPress post, this code will automatically grab the first image in your post and set it as your featured image. You can simply drop this code into your active theme's functions.php file and you are all set.

function autoset_featuredimage() {
	global $post;
	$already_has_thumb = has_post_thumbnail($post->ID);
		if (!$already_has_thumb)  {
		$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
			if ($attached_image) {
				foreach ($attached_image as $attachment_id => $attachment) {
				set_post_thumbnail($post->ID, $attachment_id);
			}
		}
	}
} 
add_action('the_post', 'autoset_featuredimage');
add_action('save_post', 'autoset_featuredimage');
add_action('draft_to_publish', 'autoset_featuredimage');
add_action('new_to_publish', 'autoset_featuredimage');
add_action('pending_to_publish', 'autoset_featuredimage');
add_action('future_to_publish', 'autoset_featuredimage');

Now your clients don't have to mess up your nice custom built front page that utilizes featured images from posts when they forget to set the image.

Adding Per-Post CSS to WordPress

customcss

Sometimes when I'm creating a post or a page in WordPress, I want to do something specific with CSS. And I really don't want to jump back and forth with Coda, my editor. So, I decided to use this little piece of code to create a Custom CSS Meta Box appear right under my WordPress post/page editor that would allow me to type my CSS selectors and declarations right on the post/page. Now, the CSS I place in the Custom CSS Meta Box will ONLY appear on that specific page or post. This idea is accomplished in four little PHP functions that can be placed in your active theme's functions.php file.

The first function creates the ability to add the meta boxes to the pages and posts. ProTip: Just add additional lines of code to add this meta box to Custom Post Types.

function bb_custom_css_hooks() {
	add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'post', 'normal', 'high');
	add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'page', 'normal', 'high');
}

The next function creates the text areas of the meta box so that we can input our custom css. It also ties the CSS typed into the meta box to that specific post/page ID.

function custom_css_input() {
	global $post;
	echo '<input type="hidden" name="custom_css_noncename" id="custom_css_noncename" value="'.wp_create_nonce('custom-css').'" />';
	echo '<textarea name="custom_css" id="custom_css" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_css',true).'</textarea>';
}

Then we need to be able to save the CSS that we type into the meta box, so we add the content from the Custom CSS meta box to the post meta area.

function bb_save_custom_css($post_id) {
	if (!wp_verify_nonce($_POST['custom_css_noncename'], 'custom-css')) return $post_id;
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
	$custom_css = $_POST['custom_css'];
	update_post_meta($post_id, '_custom_css', $custom_css);
}

Now we need a way to insert the correct Custom CSS into the header of the specific page or post that has content entered into the Custom CSS meta box.

function bb_insert_custom_css() {
	if (is_page() || is_single()) {
		if (have_posts()) : while (have_posts()) : the_post();
			echo '<style type="text/css">'.get_post_meta(get_the_ID(), '_custom_css', true).'</style>';
		endwhile; endif;
		rewind_posts();
	}
}

Finally, we hook all of these functions into the necessary WordPress hooks using add_action.

add_action('admin_menu', 'bb_custom_css_hooks');
add_action('save_post', 'bb_save_custom_css');
add_action('wp_head','bb_insert_custom_css');

If you want the full code, I've made a PasteBin file for all to use.