How to Add an Announcement Box to Your Wordpress Theme


Build an announcement box controlled by a custom dashboard panel
If you’ve been following this blog for over a month, chances are that you’ve seen our announcement box in action. What you may not realize, is just how we control that box.

In today’s tutorial we’ll build a similar announcement box into a custom Wordpress theme. It will be controlled from the dashboard, and can be switch on/off while changing the text included without having to edit the source code.

Alert box in action

This will be done by adding a custom menu (options) panel to contain all the controls. So we can focus on the announcement box more, we’ll be basing this tutorial off the walk-through “Create an Options Page for Your Wordpress Theme” found on the ThemeForest blog.

Setup Initial Functions

Below is the modified PHP that should be placed into your functions.php file to add our options panel. While this has been adapted from the code found on ThemeForest, keep in mind that some of the function names and variable values have been changed for this tutorial.

Copy the code below into your file, and meet down below for the breakdown of what’s been changed.

<?php
//Theme Control Panel
$themename = "Classic Demo"; //For labeling panels
$shortname = "demo"; //Prefix for database rows

//Define default functions folder
$functions_path = TEMPLATEPATH . '/functions/';

//Load in options array
require_once ($functions_path . 'theme-options.php');

function demo_add_admin(){

	global $themename, $shortname, $options;

	if ( $_GET['page'] == basename(__FILE__) ) {

		if ( 'save' == $_REQUEST['action'] ) {

	   	foreach ($options as $value) {
	      	update_option( $value['id'], $_REQUEST[ $value['id'] ] );
			}

	      foreach ($options as $value) {
	      	if( isset( $_REQUEST[ $value['id'] ] ) ) {
					update_option( $value['id'], $_REQUEST[ $value['id'] ]  );
				} else {
					delete_option( $value['id'] );
				}
			}

	      header("Location: admin.php?page=functions.php&saved=true");
	      die;

		} else if( 'reset' == $_REQUEST['action'] ) {

	   	foreach ($options as $value) {
	      	delete_option( $value['id'] );
			}

	      header("Location: admin.php?page=functions.php&reset=true");
	      die;

		}
	}

	//Add a new top level menu
	add_menu_page($themename, $themename, 'edit_themes', basename(__FILE__), 'interface_page');

} //End of demo_add_admin function

function interface_page(){

    global $themename, $shortname, $options;

    if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
    if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>';

?>

<div class="wrap">
	<h2><?php echo $themename; ?> settings</h2>

	<form method="post">

	<?php foreach ($options as $value) { 

		switch ( $value['type'] ) {

			case "open":
	?>
      	<table width="100%" border="0" style="background-color:#eef5fb; padding:10px;">

		<?php break;

		case "close":
		?>

        </table><br />

		<?php break;

		case "title":
		?>
		<table width="100%" border="0" style="background-color:#dceefc; padding:5px 10px;"><tr>
        	<td colspan="2"><h3 style="font-family:Georgia,'Times New Roman',Times,serif;"><?php echo $value['name']; ?></h3></td>
        </tr>

		<?php break;

		case 'text':
		?>

        <tr>
            <td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td>
            <td width="80%"><input style="width:400px;" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?>" /></td>
        </tr>

        <tr>
            <td><small><?php echo $value['desc']; ?></small></td>
        </tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;"> </td></tr><tr><td colspan="2"> </td></tr>

		<?php
		break;

		case 'textarea':
		?>

        <tr>
            <td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td>
            <td width="80%"><textarea name="<?php echo $value['id']; ?>" style="width:400px; height:200px;" type="<?php echo $value['type']; ?>" cols="" rows=""><?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?></textarea></td>

        </tr>

        <tr>
            <td><small><?php echo $value['desc']; ?></small></td>
        </tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;"> </td></tr><tr><td colspan="2"> </td></tr>

		<?php
		break;

		case 'select':
		?>
        <tr>
            <td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td>
            <td width="80%"><select style="width:240px;" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>"><?php foreach ($value['options'] as $option) { ?><option<?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['std']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option><?php } ?></select></td>
       </tr>

       <tr>
            <td><small><?php echo $value['desc']; ?></small></td>
       </tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;"> </td></tr><tr><td colspan="2"> </td></tr>

		<?php
        break;

		case "checkbox":
		?>
            <tr>
            <td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td>
                <td width="80%"><? if(get_settings($value['id'])){ $checked = "checked=\"checked\""; }else{ $checked = ""; } ?>
                        <input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> />
                        </td>
            </tr>

            <tr>
                <td><small><?php echo $value['desc']; ?></small></td>
           </tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;"> </td></tr><tr><td colspan="2"> </td></tr>

        <?php 		break;

}
}
?>

<!--</table>-->

		<p class="submit">
			<input name="save" type="submit" value="Save changes" />
			<input type="hidden" name="action" value="save" />
		</p>
	</form>

	<form method="post">
		<p class="submit">
			<input name="reset" type="submit" value="Reset" />
			<input type="hidden" name="action" value="reset" />
		</p>
	</form>

<?php }

//Activate the functions to add options panel
add_action('admin_menu', 'demo_add_admin')

?>

Note: If you’re looking for a more generalized breakdown of what’s happening in the code below, I recommend referencing the original post for help. This tutorial will not be covering the basics of adding options panels.

Another difference from the original post is the type of options page created. In the ThemeForest demo, the options panel is attached to the “Appearance” section via the add_theme_page method. In this tutorial we’re just going to make the panel its own sidebar option. This will make it easier to access as well as give some bolder personalized touch to the dashboard. This is done using the add_menu_page method instead.

Add Announcement Options

If you’re referencing the ThemeForest post, you’ll notice that I’ve separated the options array into its own PHP file and then used require_once to include it. This is a matter of personal taste, but I’ve seen this done on many more advanced themes and find that it keeps things easy to maintain. In this example, our options array is contained in functions/theme-options.php for organization sake.

You’ll need to make the folder and theme-options file in the theme’s folder. When in doubt, you can always reference this example’s source files if you’re lost. Once you’ve made the theme-options.php file, paste in the following:

<?php

	//Options for the theme specific panel

	$options = array (

		array( 	"name" => "Interface",
					"type" => "title"),

		array(	"type" => "open"),

		array(	"name" => "Alert Box Active",
					"desc" => "Show your announcement?",
					"id" => $shortname."_announcement_active",
					"std" => "false",
					"type" => "checkbox"),

		array(	"name" => "Alert Box Text",
					"desc" => "Announcement text goes here",
					"id" => $shortname."_announcement_text",
					"std" => "",
					"type" => "text"),

		array(	"type" => "close")

	); // End of options array

?>

This code is responsible for creating the options array, which will ultimately determine what is being displayed on our custom dashboard panel. In this case, we’re adding a title, check box to toggle the announcement’s visibility, and a text box to enter the contents of the announcement.

By this point you should see our custom options panel showing up in your dashboard. Hopefully your result looks something like this (Click for larger version):

Wordpress Dashboard view


Style the Box

Assuming you want the box to stick out, you’ll need to add some CSS to the paragraph class “announcement”. Here’s the styles used in the example:

p.announcement{clear:both; overflow:hidden; padding: 12px; background: #FFFABF; border: 1px solid #FFF15F; margin:0px 0px 15px 0px; font-size:14px;}

Add To Template File

At this point, you should have a fully functioning announcement system ready to go. But before it can actually be put to use, you’ll need to include it into your theme’s template files. I’ve chosen to make the announcement box a specially styled paragraph with a class of “announcement”, but you can use any other tag(s) you wish.

Paste the following loop into the template files where you’d like the announcment box to display:

<?php
	//Show any active announcment
	$announce = get_option('omr_announcement_active');
	if ($announce == "true"){
		echo '<p class="announcement">'.stripslashes(get_option('demo_announcement_text')).'</p>';
	};
?>

The conditional statement above simply checks that the alert is active, and then displays the text accordingly.

Download the Result

I know there was a lot of ground covered across two tutorials, and some of you may be lost. To help clear things up further, I’ve included the source files below in the form of a full modified theme. If you’d like to see the end result in action, simply activate this theme on your Wordpress installation.

Conclusion

Also because this kind of stuff tends to be confusing, if you have any questions or need further clarification please leave a comment below. We’ll do our best to set you straight.

We’ve found the announcement box extremely useful to have integrated into our theme, especially when we’re running a contest or need to spread a message quickly. Have any other good ideas for uses? Let us know in the comments.

  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Zach Dunn

Zach is web designer/developer for One Mighty Roar from Massachusetts, USA. He is currently studying Multimedia Web Design & Development at the University of Hartford. Follow him on Twitter @zachdunn.

 

Discussion

  1. Tommy Day

    July 7th, 2009 at 2:44 PM

    Thats awesome!

  2. Gopal Raju

    July 7th, 2009 at 3:32 PM

    Useful!

    Gopal Raju
    productivedreams,
    twitter.com/gopalraju
    .-= Gopal Raju´s last blog ..10 CSS properties that ‘were’ impossible to implement in IE6 =-.

  3. Dan Harper

    July 7th, 2009 at 4:47 PM

    Nice to see my theme options tutorial is still getting used and shared :)
    .-= Dan Harper´s last blog ..The Jobs Board =-.

  4. Ksail

    July 7th, 2009 at 4:53 PM

    Thank you for this lesson. I am happy that not necessary to use additionally javascript`s or something other
    .-= Ksail´s last blog ..Новая биржа Indek.ru =-.

  5. Danh ba web 2.0

    July 8th, 2009 at 7:56 AM

    Very useful, thanks a lot
    Keep up !

  6. Zach Dunn

    July 8th, 2009 at 11:12 AM

    @Dan Harper

    Your tutorial was instrumental in helping me figure out how to build theme panels, so it was only natural that it be the starting point for things like this.

    Hats off to you sir, it’s well deserved.

  7. Raju

    July 8th, 2009 at 11:45 AM

    very nice and useful… am just a bit lost with options panel, how i wish someone comes up with the plugin version :D

  8. Christy

    July 8th, 2009 at 12:18 PM

    I created an announcements box using a php code plugin, a widget box (from the plugin), a category just for announcements, and a limit of 1 post. So the blog/site administrator need not ever touch code and I did not touch the templates. It also shows photos and the post contents. Just create a new post under the announcements category and it appears on the site. Also, you can republish older posts when you want repeat announcements. And you have all of the drag and drop features of a widget to move it around or remove it in an instant.
    .-= Christy´s last blog ..Possibilities – Original =-.

  9. Kawsar Ali

    July 8th, 2009 at 4:17 PM

    As usual very cool wordpress post. Good job
    .-= Kawsar Ali´s last blog ..30 Beautiful Wood Inspired Websites and 200+ “Woody” Resources =-.

  10. Matt

    July 9th, 2009 at 7:17 AM

    Amazing.. I have always dreaded messing with the functions.php but not any more! amazing guides like this are… FREE!!! thank you for taking the time to write this Zach!
    M@

  11. Henning

    July 14th, 2009 at 5:39 AM

    Hi there! This would definetly be very useful rewritten as a plugin! Do you have any serious plans to offer it as ready made package?
    Cheers, Henning
    .-= Henning´s last blog ..Kunde: TV 1890 e.V. Rüsselsheim-Haßloch Segelabteilung =-.

  12. Think Flick

    July 14th, 2009 at 6:52 AM

    Amazing.. thank you for taking the time to write this Zach!

  13. Melody

    July 15th, 2009 at 12:35 PM

    You guys are bringing some of the most useful tutorials I’ve seen to the web..
    .-= Melody´s last blog ..Official T-shirt Design Line Launches Today! =-.

  14. Zach Dunn

    July 15th, 2009 at 6:48 PM

    @Henning

    I have no plans to turn this into a plugin at the moment, but you may be onto something. This might end up being my inaugural Wordpress plugin. Thanks for the suggestion!

  15. seeal

    July 19th, 2009 at 1:35 PM

    ohh!! thx for sharing¡¡ :)
    .-= seeal´s last blog ..Las 5 mejores herramientas para los diseñadores web =-.

  16. Amber

    July 26th, 2009 at 11:19 AM

    This is just what I need for a site I am working on. I have the options panel displayed but when I try to save I get the message “Are you sure you want to do this? Please try again.” Any suggestions?

    Any ideas

  17. Flex developer

    July 31st, 2009 at 7:24 AM

    very nice article…keep on the good work

  18. sebastien

    September 16th, 2009 at 9:40 AM

    If i am “editor” and no “administrator” i can’t see the button “classic demo”. If i want to see it, what can i do ? Thx

  19. Zach Dunn

    September 16th, 2009 at 10:10 AM

    @Sebastien

    The Classic Demo is simply for demonstration purposes. Editors will not be able to change themes on most installations, so I recommend that you install a local Wordpress setup and check it out from there.

  20. sebastien

    September 16th, 2009 at 12:15 PM

    I have a settings page and i need that editors could see and edit this page.

    With this line :
    add_menu_page($themename, $themename, ‘edit_themes’, basename(__FILE__), ‘interface_page’
    the administrator can see the button but not editors.

    Why can i create a button which editors can see ?

  21. Zach Dunn

    September 16th, 2009 at 1:23 PM

    @Sebastien

    That has to do with the default permissions for Wordpress users. An administrator is the only account which has top level controls about the blog theme, settings, etc. The role of an editor is on the content publishing. You can read more about it in this page of the Wordpress Codex.

  22. NeoJoe

    October 10th, 2009 at 11:24 PM

    I just got my own domain website and am a complete newbie to Wordpress, which I decided to use as my homepage.

    I tried searching google for announcement boxes, as well as the plugin search embedded in the admin panel but so far this is the only thing I’ve found that’s exactly what I want.

    Just one problem – this one isn’t a plugin!

    I’ve read the whole thing and have no idea where to start! Could anybody help me get it to work? Thanks!

    My website is http://www.Neo-Joe.com and I’ll check back here periodically for replies but if you don’t mind, you can just e-mail me at admin@neo-joe.com Thanks!
    .-= NeoJoe´s last blog ..Check out my new Twitter account! =-.

  23. PieRo

    October 23rd, 2009 at 4:15 AM

    Hello,
    IT-is possible to ad image in the admin area of the plugin ??

    thanks
    .-= PieRo´s last blog ..‘Il va y avoir du sport’ du 23/10/09 : le programme ! =-.

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!