How to Use jQuery to Show or Hide a Metabox

And now you have added a class to the metabox you just created!Adding your custom class to the each of the metaboxes, sets up the jQuery to do its thing. Here’s the simplified version:

function metabox_script() {

 wp_enqueue_script( 'jquery' );

 $script = '
<script type="text/javascript">
 jQuery(document).ready(function($) {

$("#metabox_id_name").hide();

 $("input[name$=\'input_id_name\']").click(function() {
 var type = $(this).val();

 $("div.added_class").hide();
 $("#metabox_id_name").show();
 });

 });
</script>';

 return print $script;

} // End of metabox_script()

First, the script hides the metabox with the matching id. Then, it listens to the inputs with the matching input_id_name. If the value of that input matches the added_class, then it shows that metabox. Simple enough.

In my plugin’s case, I’m creating seven metaboxes and showing and hiding just one based on the radio button selection. Instead of writing seven show/hide statements, I used this code, which is the jQuery equivalent to a foreach statement:

function metabox_script() {

 wp_enqueue_script( 'jquery' );

 $script = '
<script type="text/javascript">
 jQuery(document).ready(function($) {

 $.each(["app", "client", "gallery", "position", "site", "theme", "video"], function() {
 $( "#slushman_portfolio_" + this + "_fields" ).hide();
 });

 $("input[name$=\'slushman_portfolio_type\']").click(function() {
 var type = $(this).val();

 $("div.slushman_portfolio_type_fields").hide();
 $("#slushman_portfolio_" + type + "_fields").show();
 });

 });
</script>';

 return print $script;

} // End of metabox_script()

And there you have it. Now, your jQuery will show/hide a metabox of your choosing.

Adding a Custom Class to a Submit Button

While you can hand-code the HTML for a submit button in a form, WordPress has a nice function, submit_button(), that can drop in the correct code for you. The function accepts five arguments: $text, $type, $name, $wrap, and $other_attributes.

$text changes the text on the button.

$type determines the style of the button. The common options are primary, secondary, and delete, with primary being the default.

$name sets the name attribute for the button, its “submit” by default.

$wrap determines if the button is wrapped in paragraphs tags or not, the default is true.

$other_attributes sets other attributes for the button.

For a recent project, I wanted to restyle some buttons to make them look like links, like on the posts page, rather than buttons. While you don’t NEED an special class to pull this off, it certainly makes it easier and neater in the CSS. I thought this would be achievable in the $other_attributes, but through trial-and-error I discovered you add your custom class in $type instead of using one of the defaults, like this:

submit_button( 'Whatever Text', 'my_custom_class' );

Basically, whatever you put there will be added to the class attribute of the button and you’re good to restyle the button however you want using your custom class.

How to Add a Class to a Metabox

While developing a new plugin, I had needed to show/hide some metaboxes based on which radio button is selected from another metabox. Fortunately, I found this method and wanted to share my findings. Here’s the code you’ll need to start off with:

add_filter( 'postbox_classes_{post_type_name}_{metabox_id}, array( $this, 'add_metabox_classes' ) );

function add_metabox_classes( $classes ) {

	array_push( $classes, {class_to_add} );
	return $classes;

} // End of add_metabox_classes()

Just a note: the “array( $this,” part of the add_filter() statement is because I put all my plugins inside a class and you need to write all callback functions this way. If you’re not using a class, the add_filter() statement would be:

add_filter( 'postbox_classes_{post_type_name}_{metabox_id}, 'add_metabox_classes' );

The add_filter() statement works like this: the {post_type_name} is exactly that, the name of your post type. In my plugin, it would be “slushman_portfolio”, but if you’re doing this with the built-in WordPress posts, it would “posts”. The {metabox_id} is the id attribute of the metabox for which you want to apply the filter.

The add_metabox_classes() function grabs the $classes array and adds your additional class to the end, then returns the array. When the metabox gets created, the $classes array contains all the classes that are put into the class attribute.

Now, you’re all finished. The class you want to add to your metabox is added. I’ll write another tutorial on how to use jQuery to show or hide that metabox based on the value of the radio buttons.

How to Add the jQuery UI Datepicker to a Plugin

I recently decided to dive into jQuery and figure out how to add a Datepicker to the Seminar system plugin I’m building for the Curb College at Belmont.  Thankfully, I didn’t need to write one from scratch because jQuery UI already makes a great Datepicker and including it in a plugin is super easy.  While I owe a great deal to Zigpress’s great tutorial, the instructions are unfortunately outdated, so I’m going to update them here.

If you’re using WordPress 3.3 or higher, then the jQuery UI Datepicker is already included, otherwise you should update your WordPress install or include the files.  In either case, you will need to include a theme for the Datepicker and add a few lines of code.  FYI, all the following code samples are written within a class, which you should be doing in your plugin, but feel free to adapt as necessary.  First thing, in your __construct() function, you’ll need to add a few lines that tells the plugin to reference a function that will include the jQuery references.

Add Actions

// Add jQuery calender
add_action( 'admin_print_scripts-post.php', array( $this, 'seminar_scripts' ), 1000 );
add_action( 'admin_print_scripts-post-new.php', array( $this, 'seminar_scripts' ), 1000 );
add_action( 'admin_footer', array( $this, 'admin_footer' ) );

In my plugin, I’m using the Datepicker for a meta box on the custom post type pages in the admin area, so I’m using the actions admin_print_scripts-post.php and admin_print_scripts-post-new.php and they both call the ‘seminar_scripts’ function.  I also have the admin_footer action call the admin_footer function.  Calling the Datepicker only on the required admin pages lowers the overhead for loading the Admin pages, keeping things as small as possible without sacrificing functionality.

Enqueue the Script and Theme

Now we have to functions to define two functions: seminar_scripts() and admin_footer().

function seminar_scripts() {
   global $post_type;
   if( 'cemb_seminar' != $post_type ) { return; }
   wp_enqueue_script( 'jquery-ui-datepicker' );
   wp_enqueue_style( 'jquery.ui.theme', plugins_url( '/css/jquery-ui-1.8.17.custom.css', __FILE__ ) );
} // End of seminar_scripts()

Seminar_scripts() starts by checking what post type you’re looking at.  If it’s not cemb_seminar (my custom post type – be sure to change this to match your plugin), then stop.  If it is cemb_seminar, then enqueue the Datepicker and it’s theme.  If you use a different folder structure for your plugin, you’ll need to change the plugins_url() line to match your structure.

For now (2/23/2012), you will need to include a theme for your Datepicker.  WordPress doesn’t include a theme for the Datepicker, but that should be resolved in a coming update.  To get a theme, go to the jQuery UI ThemeRoller, select the Gallery tab on the right sidebar, and choose your theme.  I’m using Smoothness because I think it most closely matches the WordPress Admin UI.

Clicking the Download button under a theme will take you to a page where you can select options for your jQuery UI download.  Select your theme from the Theme drop menu, select the stable version, and click the Download button.

When it finishes downloading, unzip the file and go to the css > smoothness folder.  In my plugin, I’ve got a CSS folder.  Drag the jqery-ui-1.8.17.custom.css file and images folder from the zip file into your plugin’s css folder (or wherever you pointed the plugins_url() line in the enqueue statement in seminar_scripts()).

Add the jQuery Script

function admin_footer() { ?>
   <script type="text/javascript">
      jQuery(document).ready(function(){
         jQuery('.seminar_date').datepicker({
            dateFormat : 'D, m/d/yy'
         });
      });
   </script><?php
} // End of admin_footer()

Admin_footer() includes the actual jQuery statement to make things happen on the page in the footer of your admin page.  There are two things here you will need to customize for your plugin: the selector and the date format.  jQuery works by looking at the page and finding a part of the page – aka the selector – and performing the script.  My selector is the CSS class (.seminar_date) for the date field in the meta box.  You’ll need to modify that to match the CSS class (or ID) for your date field.  The date format is just how the date is printed on the page.  For my plugin, I choose a format like: Mon 2/22/2012.  You can see all the options on this page.

That’s it!  Once you’ve added all that code and uploaded the jQuery UI theme, test it out and see the Datepicker appear when you click in the field you selected in the selector.

How to Change the Welcome User Email

I recently needed to customize the welcome new user email that goes out when WordPress registers a new user. While there are several plugins that handle that, I wanted to learn how to do myself (if anything, just to learn). After comparing several plugins and code I found on StackExchange, I came up with this plugin.

<?php

/*
Plugin Name: Slushman Welcome Email
Plugin URI: http://slushman.com/plugins/slushman-welcome-email
Description: Customize the output of the welcome email sent by WordPress.
Version: 0.1
Author: Slushman
Author URI: http://slushman.com
License: GPLv2

**************************************************************************

  Copyright (C) 2011 Slushman

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General License for more details.

  You should have received a copy of the GNU General License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.

**************************************************************************

*/

// Redefine user notification function
if ( !function_exists( 'wp_new_user_notification' ) ) {

    function wp_new_user_notification( $studentID, $plaintext_pass = '' ) {

		// URLs
		$site_url = site_url();
		$seminar_url = site_url( 'seminars/' );
		$login_url = wp_login_url();
		
		// Email variables
		$student 			= new WP_User($studentID);
		$student_data 		= get_userdata( $studentID );
		$firstname 			= $student_data->first_name;
		$student_login 		= stripslashes( $student_data->user_login );
		$headers 			= 'From: CEMB Seminar System - DO NOT REPLY <seminars@curbcollege.info>' . "rn";
		$blog_name 			= get_option( 'blogname' );
		$admin_subject 		= 'New User Registration on ' . $blog_name;
		$welcome_subject 	= 'Welcome to the CEMB Seminar system!';
		$welcome_email		= stripslashes( $student_data->user_email );
		$admin_email		= get_option('admin_email');
		
		$admin_message = 
<<<EOT

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	</head>
	<body>
		<div class="content">
			<div class="wrapper">
				<p>New user registration on your blog: {$blog_name}.</p>
				<p>Username: {$student_login}</p>
				<p>Email: {$welcome_email}</p>
			</div><!-- End of wrapper -->
		</div><!-- End of content -->
	</body>
</html>

EOT;
	
		$welcome_message = 
<<<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	</head>
	<body>
		<div class="content">
			<div class="wrapper">
				<table width="100%" border="0" cellspacing="0" cellpadding="0">
					<tr>
						<td align="center" valign="middle" bgcolor="#141415"><img src="http://makemeanexpert.com/beta.curbcollege.info/wp-content/uploads/2011/08/header.jpg" /></td>
					</tr>
					<tr>
						<td><br /><br />
							Hello {$firstname},<br />
							<br />
							Welcome to the new CEMB Seminar system! You can log in to change your password and email address, as well as see your seminar credits and which seminars you've attended.  When you receive credit for attending a seminar, you will recieve an email confirming your attendance credit, how many credits you've earned so far, and any upcoming seminars (if you still need some credits).<br />
							<br />
							To log into your account, go <a href="{$login_url}">visit the new seminar site</a> and use the credentials below.<br />
							<br />
							Your Username: {$student_login}<br />
							Your Password: {$plaintext_pass}<br />
							<br />
							See you at seminar!<br /><br />
						</td>
					</tr>
					<tr>
						<td style="background-color:#141415;">
							<table width="100%" border="0" cellspacing="0" cellpadding="0">
								<tr>
									<td colspan="3">
										<center><img src="http://makemeanexpert.com/beta.curbcollege.info/wp-content/uploads/2011/08/emailfooter.jpg" style="width:700px;height:80px;" style="align:center;" /></center>
									</td>
								</tr>
								<tr>
									<td align="right" valign="center">
										<a href="{$site_url}" style="color:#fffffe !important;width:234px;">Curb College Info</a>
									</td>
									<td align="center" valign="center">
										<a href="{$seminar_url}" style="color:#fffffe !important;width:234px;">Seminar Page</a>
									</td>
									<td align="left" valign="center">
										<a href="{$login_url}" style="color:#fffffe !important;width:234px;">Seminar Login</a>
									</td>
								</tr>
							</table>
						</td>
					</tr>
				</table>
			</div><!-- End of wrapper -->
		</div><!-- End of content -->
	</body>
</html>
EOT;

		wp_mail( $admin_email, $admin_subject, $admin_message, $headers );
		wp_mail( $welcome_email, $welcome_subject, $welcome_message, $headers );

	} // End of wp_new_user_notification()
	
} // End of 'if wp_new_user_notification doesn't exist'
	
?>

Thankfully, wp_new_user_notification is a pluggable function, which means it can be overridden with a plugin. This simple plugin replaces that function and allows you to customize the HTML however you need it displayed. There’s no admin page for it, you simply edit the HTML in the file itself, save it (or update it if you’re using the Plugin Editor in WordPress), and your new welcome message will be shown when a new user is registered.

I chose to use the heredoc technique for the message for the simplicity. Any PHP variables you surround with brackets and put in the HTML will be replaced with the variable’s value, so it’s much simpler to figure out how the message will appear to the user.

How to Set Dashboard to Use One Column

I’m working on a plugin for Belmont where I need the Dashboard to have one column for all users.  While I could log into every user and change their Screen Options to one column, it would take next to forever with thousands of students accessing this site.  Thankfully, I found this bit of code on Stackexchange (thanks sorich87!) and modified it for the Dashboard page.  This will force all users to have one column on the Dashboard.

function so_screen_layout_columns( $columns ) {

$columns['dashboard'] = 1;

return $columns;

}

add_filter( 'screen_layout_columns', 'so_screen_layout_columns' );

function so_screen_layout_dashboard() {

return 1;

}

add_filter( 'get_user_option_screen_layout_dashboard', 'so_screen_layout_dashboard' );

Find User ID by User MetaData

I just wrote this useful function and thought I’d share.  I’m working on a plugin for my employer, Belmont University, and I needed to find a user’s ID by the user’s barcode, which is stored as user metadata.  There’s not a built-in WordPress function to handle that, but this custom function works nicely.  You can add it to your theme’s functions.php file or to a plugin file (in my case, this is part of plugin).  Here’s the function:

function get_user_by_metadata( $metafield, $metavalue ) {

	// Look up user's metadata.
	$users = get_users( array( 'meta_key' => $metakey, 'meta_value' => $metavalue ) );

	// Return the user's WordPress ID
	foreach ($users as $user) {
	    echo $user->ID;
	}

} // End of get_user_by_metadata()

To print the value on the screen, call the function (within a class) like this:


$metavalue = '100072659';
$metakey = 'buidbarcode';
$user = $this->get_user_by_metadata( $metakey, $metavalue );
return $user;

How to Hide the BuddyPress Admin Bar (aka BuddyBar)

I’ve seen a bunch of sites that supposedly show you how to do this, but none are complete.  I have a client who wants to use BuddyPress, but doesn’t want the Admin Bar (I call it the BuddyBar) across the top of every page.  So I’m building a plugin called BuddyBar Widget that includes a sidebar widget with all the BuddyBar links in it.  Another part of the plugin hides the BuddyBar completely, even when you’re on Dashboard.

To hide the BuddyBar from users that aren’t logged in, go to the BuddyPress General Settings page and select “Yes” for the Hide admin bar for logged out users? option.

That’s great, but it doesn’t hide it if you ARE logged in.  For that, we’ll need some code.

EDIT ( February 1, 2012):

Ignore the old post from below. After trying to get that to work properly, I’ve switched to something far more effective. Paste the code snippet below into your wp-config.php file. I put it right above the “Authentication Unique Keys and Salts.” comment block. THis works for sure. It’s not what I had hoped to do, but it works.

/** Disable the WP Admin Bar */
define('BP_DISABLE_ADMIN_BAR', true);



CODE BLOCK REMOVED


I created a function (I'm calling it remove_buddyadminbar), then used define to tell WordPress to turn off the BuddyBar.  This, by itself, will turn off the BuddyBar.  It may complete overkill, but I also use remove_action hooks as well.  BuddyPress uses the add_action hook in the WordPress footer to activate the BuddyBar.  Remove_action simply negates that call from BuddyPress.  You'll notice, I also include the call for the admin_footer, which should hide the bar on your admin pages, including Dashboard.

While that's all well and good, now you'll notice a nice gap at the top of your admin pages.  When you kill the BuddyBar for the Dashboard, it doesn't undo the CSS formatting that creates room for it at the top of your admin pages.  This bit of CSS takes care of that:
CODE BLOCK REMOVED


Using those two bits of code will completely eliminate the BuddyBar from appearing on your site.  I'll post again about this when the plugin is ready to ship.