- WordPress 3 Plugin Development Essentials
- Brian Bondari Everett Griffiths
- 956字
- 2021-04-09 21:19:58
User-defined functions
Each plugin will store the majority of its code inside functions that you define. While it is technically possible to have a plugin that has nothing but a header, or to have a plugin that does not use user-defined functions, it is highly unlikely you would ever write such a plugin outside of a purely academic exercise.
Ready to proceed? Let's make a doomed plugin.
Exercise—an evil functionless plugin
You may not be used to writing your own functions in your code, especially for trivial tasks. However, when you are writing WordPress plugins, it is virtually impossible to get away with having all your code naked in the main code block. Let's take a closer look at how WordPress works and you will see why you need to shepherd your code into functions.
Normal users will use the Add New button in the Dashboard to search the WordPress repository for published plugins, but we as developers will be creating our own plugins from scratch. To do this, all we need is our trusty text editor (and our FTP client to upload it to the web server, if you're running WordPress remotely).
This exercise will illustrate how not to code a plugin:
- Create a new PHP file inside the
/wp-content/plugins
directory. In this example, we've named oursevil-example.php
. - Copy the <?php opening tag and the header information from the "Hello Dolly"
hello.php
file and take a moment to customize the header. - Add a single print statement to your plugin and save it. The following is what our full example looks like:
<?php /* Plugin Name: Bad Example Plugin URI: http://wordpress.org/# Description: Showing what NOT to do. Author: Everett's Twin from an Evil Parallel Universe Version: 0.666 Author URI: http://goo.gl/us9i */ // Worst plugin ever print " -------- I think I'm getting a clue!"; /* End of File */
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Note
In case you didn't notice, we have omitted the closing ?> tag. We'll explain why, later in this chapter.
- Once you've saved your new plugin, head back to your browser and refresh the Plugin admin page. Your new plugin should appear on the list, as follows:
- As soon as you activate the plugin, a few horrible things may happen.
- You may see a PHP warning, such as Cannot modify header information….
- WordPress itself may show you a warning, as follows:
The plugin generated 37 characters of unexpected output during activation. If you notice "headers already sent" messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

You will see the text you printed at the top of every page on your site, including your home page! This obnoxious text appears before the opening HTML and DOCTYPE tags.
What just happened
This is a pretty simple script, so why did everything explode? If you already know the answer, keep quiet for the folks who are still figuring this out. The answer will help keep you out of trouble when writing PHP code.
Before we go any further, if you did not see the PHP errors, then you really need revisit the previous chapter on setting up your environment and debugging. This will be your last reminder.
Now, to answer the question of all those header errors—what's going on? The whole point of using a hook is to have your function executed at a certain time. When you include a file, its code is parsed and any code not inside classes or function-blocks gets executed (whereas the classes and functions are merely loaded). The problem here revolves around PHP's header()
function, which WordPress is using to declare the content type of its output—for example, the scripts generating the main pages use the text/HTML content type, whereas the scripts generating the RSS feeds use an RSS/XML content type.
All you really need to understand here is that the header()
function must be called before any output is sent. From PHP's documentation:
"Remember that
header()
must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP."
It also warns that header errors are common when using include()
or require()
functions. A brief analogy is seen when you mail a letter—you must address the envelope before you drop it into the mailbox.
Consider the following two scripts:
Example 1
<?php header('Content-type: text/plain'); print "Headers come first."; /* End of File */
Example 2
<?php print "This will raise a warning."; header('Content-type: text/plain'); /* End of File */
The first example works normally—if you uploaded this to the root of your website and named it test.php
, then loaded it in your browser (for example, http://yoursite.com/test.php
), you would see the printed text. However, the second example generates the now familiar PHP warning: Cannot modify header information. It's as if you are trying to change the address on your letter after you posted it.
Back in our "Bad Example" plugin, this is exactly what was happening. The print statement was executed when the file was included, and this jumped the gun on the header()
function, even though the code was otherwise syntactically correct. Our "Bad Example" is, in fact, a good example of what not to do. This should help drive home the point that you must define your own functions in order to write WordPress functions—you cannot simply put naked code into your plugin file.
Omitting the closing "?>" PHP tag
So why do we omit the closing tag in our plugins? PHP will automatically terminate a file with a closing ?> tag if needed, but we're not just being lazy here. The reason is predicated on our discussion about headers—if your plugins have any trailing whitespace after the closing ?>, it gets interpreted in the same way as if you had printed something, and that can cause the same header warnings. Look closely at the following example. Notice the extra lines after the closing PHP tag?

It is exceedingly difficult to spot extra newlines or spaces when debugging a script, so we omit the closing PHP tags whenever possible simply because they may trigger header errors. It is helpful to include a comment at the end of the file, such as /*End of File*/
or simply /*EOF*/
just as a reminder that yes, the omission is intentional and not the result of a corrupted file.
A better example: Adding functions
Now that we know what we can't simply print data directly from our plugin's main block, let's fix our example to make it a bit more like the "Hello Dolly" plugin:
<?php /* Plugin Name: Better Example Plugin URI: http://wordpress.org/# Description: Undoing the Madness Author: Everett's sometimes obnoxious Twin Version: 0.7 Author URI: http://theonion.com/ */ function safe_print() { print " -------- I think I'm getting a clue!"; } /* End of File */
What's different about this example? This version of our plugin isolates the print statement inside a function block so that it does not execute immediately once the file is loaded. If you change the code in your sample plugin and save it, the warnings caused by the previous version of this plugin should disappear once you refresh the page. This gets us out of trouble, but it doesn't get our statement printing and visible just yet. To do that, we must add a hook to trigger execution of our function.
- Beginning Swift
- 持續演進的Cloud Native:云原生架構下微服務最佳實踐
- Creo 4.0中文版從入門到精通
- Visio圖形設計從新手到高手(兼容版·第2版)
- Photoshop CS6完全自學案例教程(微課版)
- Mastering phpMyAdmin 3.3.x for Effective MySQL Management
- 跟儲君老師學Excel極簡思維
- PyTorch深度學習簡明實戰
- SketchUp/Piranesi印象彩繪表現項目實踐
- 印象筆記留給你的空間2.0:個人知識管理實踐指南
- 用Cubase輕松制作你的短視頻音樂
- Photoshop CC 2018基礎教程(第3版)
- Photoshop CS6數碼照片處理入門到精通
- 剪映:零基礎輕松掌握手機剪輯短視頻
- JBoss AS 5 Performance Tuning