How to Add an Announcement Box to Your WordPress Theme

How to Add an Announcement Box to Your WordPress Theme


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.

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:

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:

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:

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.

Posted Tuesday, July 7th, 2009 · Back to Top

SPONSOR

Add Comment

44 Comments 30 Mentions

  1. Tommy Day Author Editor

    Thats awesome!

    ·

    • Candid Author Editor

      If you wrote an atrlice about life we’d all reach enlightenment.

      ·

  2. Gopal Raju Author Editor

    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 Author Editor

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

    ·

  4. Ksail Author Editor

    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 Author Editor

    Very useful, thanks a lot
    Keep up !

    ·

  6. Zach Dunn Author Editor

    @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 Author Editor

    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 Author Editor

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

    ·

    • Latrice Author Editor

      Shiver me timbers, them’s some great inforamoitn.

      ·

  9. Kawsar Ali Author Editor

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

    ·

  10. Matt Author Editor

    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 Author Editor

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

    ·

    • Zach Dunn Author Editor

      @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!

      ·

  12. Think Flick Author Editor

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

    ·

  13. Melody Author Editor

    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. seeal Author Editor

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

    ·

  15. Amber Author Editor

    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

    ·

  16. Flex developer Author Editor

    very nice article…keep on the good work

    ·

  17. sebastien Author Editor

    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

    ·

    • Zach Dunn Author Editor

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

      ·

  18. sebastien Author Editor

    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 ?

    ·

    • Zach Dunn Author Editor

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

      ·

  19. NeoJoe Author Editor

    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 [email protected] Thanks!
    .-= NeoJoe´s last blog ..Check out my new Twitter account! =-.

    ·

  20. PieRo Author Editor

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

    ·

  21. Oleg Author Editor

    KIEV Requests
    KIEV Invites TO Respite

    ·

  22. Oleg Author Editor

    Split on-kievski Frequently
    Slash on top of-kievski

    Habitually without stopping the Internet next to medium I get the drift dwells in who prepared ry bite of|every|entirely] engage in furthermore option – in the direction of taunt en route for swallow possess back-to-back. Hence are vastly application

    ·

  23. Oleg Author Editor

    Cleft never-endingly-kievski Frequently
    Fee scheduled-kievski

    Frequently arrange the Internet by meetings I get the message makes somewhere your home who position ry bite of|every|entirely] enclose additionally risk – in the direction of dare towards approve of confess studio. Therefore are exceptionally entitlement

    ·

  24. Дмитрий Author Editor

    Славные среди знаменитостей лайбы
    Популярные среди знаменитостей велики
    Знакомые и высокородные люди все чаще находят пышущий здоровьем образ жизни.

    ·

  25. Саша Author Editor

    Велосипедный сайт КиргизииНа этом портале вы смогете найти полную инфу по велосипедному спорту!

    ·

  26. Саша Author Editor

    Велоспортивный портал КыргызстанаНа этом интернет-ресурсе вы смогете разыскать всю информацию по велоспорту!

    ·

  27. Саша Author Editor

    Вело сайт КыргызстанаНа этом ресурсе вы сможете разыскать всю информацию по велоспорту!

    ·

  28. Кирил Author Editor

    Портал про сбор дошколят!
    Сайт про подготовку дошкольников! Здесь легко выбрать не имеющую границ оповещение о полных этапах подготовки детей.

    ·

  29. Виталий Author Editor

    Сайт Иссык куль!
    Сайт Иссык куль, это пост сконцентрированности всей толстушки у озерка Иссык куль, на этом!

    ·

  30. Саша Author Editor

    Велосипедный ресурс КыргызстанаНа этом ресурсе вы смогете обнаружить объективную инфу по велоспорту!

    ·

  31. Jay Gilford Author Editor

    Well I was enjoying reading some of these comments and then it was spam spam spam lol. One word for you guys – Akismet

    ·

    • Tida Author Editor

      I was doing the same .. and spam spam spam!
      :P

      It’s nice post anyway :)

      ·

  32. Andry Author Editor

    HELP CHILDREN OF UKRAINE AND GEORGIA! Children in need! DONATE EDUCATIONAL MATERIALS TO CHILDREN IN IMPOVERISHED COUNTRIES! In some parts of the world, educational materials such as books, paper, pencils, rulers and erasers are scarce and expensive. Donate now to help children in need.
    On-line Payment Solution
    WebMoney
    account of USD: WMZ 351241998583
    account of EUR: WME 802714109738

    ·

  33. Mr LE Author Editor

    Hello! I’ve tried to make this work, but there is no alert box drawn no matter what I do. I use WP 3.0 – does that have anything to do with it?
    This tutorial is very useful, but it just doesnt work. No errors, but just blank.

    Could you please assist? this is exactly what I’ve been looking for!

    ·

  34. dd Author Editor

    Hi, very useful bur it I confirm Mr LE, it doesn’t work with WP 3.1 :(
    So is there an update to make it works ? Thanks

    ·

  35. ferrio Author Editor

    Строю сейчас дом, и мне нужны [url=http://arki-mebel.ru/katalog/ellips]арки[/url], и вот сам вопрос, а нужны ли они или можно обойтись чем-то другим, чтобы было покрасивее?

    ·

  36. tosaathkaqyys Author Editor

    Где недорого купить картридж Canon 728?
    Лазерные картриджи Brother.
    У нас Вы всегда можете купить недорогой лазерный картридж Canon 728.

    [url=http://www.filpan.ru] Дешевые лазерные картриджи Canon 728 [/url] для лазерных принтеров и копиров.
    Всегда в наличии : заправка картриджей xerox, недорогие лазерные картриджи.
    У нас Вы всегда найдете заправка картриджей Konica-minolta и недорогие лазерные картриджи Canon 728.
    [url=http://www.filpan.ru]Заправка картриджа с выездом аппарата Samsung SCX 4623 , Xerox WC 3210 , Xerox WC 3100 , Xerox WC 3300 , Xerox WC 114 , HP СЕ278А , HP CE505A , Samsung SCX 4220 , Samsung MLT -108 S , Samsung MLT-D208. [/url]

    ·

  37. Zefealkeliona Author Editor

    For example, a prescription for lansoprazole can be filled [url=http://spironolactone.webs.com/]spironolactone no prescription[/url] Prescriptions may be issued for drugs specifying only the chemical name,

    By extension, therefore, generics are considered [url=http://mexicozyprexa.webs.com/]discount no prescription zyprexa[/url] For example, a prescription for lansoprazole can be filled

    ·

  38. fast approve Author Editor

    Hello, I read your new stuff on a regular basis.
    Your story-telling style is witty, keep up the good work!

    ·

 

Build Internet by One Mighty Roar. Since 2008.