Tải bản đầy đủ (.pdf) (1,323 trang)

Professional wordpress plugin development

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.98 MB, 1,323 trang )


CONTENTS
Foreword
Introduction
Chapter 1 : An Introduction to Plugins
What is a Plugin?
Available Plugins
Advantages of Plugins
Installing and Managing Plugins
Summary
Chapter 2 : Plugin Foundation
Creating a Plugin File
Sanity Practices
Header Requirements
Determining Paths
Activate/Deactivate Functions
Uninstall Methods
Coding Standards

2


Plugin Development Checklist
Summary
Chapter 3 : Hooks
Actions
Filters
Using Hooks from Within a Class
Creating Custom Hooks
How to Find Hooks
Summary


Chapter 4 : Integrating in WordPress
Adding Menus and Submenus
Creating Widgets
Meta Boxes
Keeping It Consistent
Summary
Chapter 5 : Internationalization
Internationalization and Localization

3


Creating Translation Files
Summary
Chapter 6 : Plugin Security
Securing Your Plugin
User Permissions
Nonces
Data Validation and Sanitization
Formatting SQL Statements
Security Good Habits
Summary
Chapter 7 : Plugin Settings
The Options API
The Settings API
The Transients API
Saving Per-User Settings
Storing Data in Custom Tables
Summary


4


Chapter 8 : Users
Working with Users
Roles and Capabilities
Limiting Access
Customizing Roles
Summary
Chapter 9 : HTTP API
HTTP Requests Crash Course
WordPress’ HTTP Functions
Practice: Reading JSON from a Remote API
Practice: Sending Data to a Remote API
Practice: Reading Arbitrary Content
Make Your Own Plugin Repository
Special Case: Fetching Remote Feeds
Summary
Chapter 10 : The Shortcode API
Creating Shortcodes

5


Shortcode Tips
Integrating Google Maps
More Shortcode Quick Ideas
Summary
Chapter 11 : Extending Posts: Metadata, Custom Post Types,
and Taxonomies

Creating Custom Post Types
Using Custom Post Types
Post Metadata
Creating Custom Taxonomies
Using Custom Taxonomies
A Post Type and Taxonomy Plugin
Summary
Chapter 12 : JavaScript and Ajax in WordPress
jQuery–A Brief Introduction
Ajax
Adding JavaScript in WordPress
Ajax in WordPress
6


Summary
Chapter 13 : Cron
What is Cron?
Scheduling Cron Events
True Cron
Practical Use
Summary
Chapter 14 : The Rewrite API
Why Rewrite URLs
How WordPress Handles Queries
Practical Uses
Summary
Chapter 15 : Multisite
Differences
Enabling Multisite in WordPress

Multisite Functions
Multisite Database Schema

7


Summary
Chapter 16 : Debugging and Optimizing
Supporting Old Versions (Not)
Debugging
Error Logging
Caching
Summary
Chapter 17 : Marketing Your Plugin
Choosing a License for Your Plugin
Submitting to WordPress.org
Getting Your Plugin Renowned
Summary
Chapter 18 : The Developer Toolbox
Core as Reference
Codex
Tool Web Sites
Community Resources

8


Tools
Summary
Index


9


10


11


Professional WordPress® Plugin Development
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2011 by Wiley Publishing, Inc., Indianapolis,
Indiana
Published simultaneously in Canada
ISBN: 978-0-470-91622-3
ISBN: 978-1-118-07530-2 (ebk)
ISBN: 978-1-118-07532-6 (ebk)
ISBN: 978-1-118-07531-9 (ebk)
No part of this publication may be reproduced, stored in a
retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or
otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior
written permission of the Publisher, or authorization through
payment of the appropriate per-copy fee to the Copyright

Clearance Center, 222 Rosewood Drive, Danvers, MA 01923,
12


(978) 750-8400, fax (978) 646-8600. Requests to the
Publisher for permission should be addressed to the
Permissions Department, John Wiley & Sons, Inc., 111 River
Street, Hoboken, NJ 07030, (201) 748-6011, fax (201)
748-6008, or online at />Limit of Liability/Disclaimer of Warranty: The publisher and
the author make no representations or warranties with respect
to the accuracy or completeness of the contents of this work
and specifically disclaim all warranties, including without
limitation warranties of fitness for a particular purpose. No
warranty may be created or extended by sales or promotional
materials. The advice and strategies contained herein may not
be suitable for every situation. This work is sold with the
understanding that the publisher is not engaged in rendering
legal, accounting, or other professional services. If
professional assistance is required, the services of a
competent professional person should be sought. Neither the
publisher nor the author shall be liable for damages arising
herefrom. The fact that an organization or Web site is referred
to in this work as a citation and/or a potential source of
further information does not mean that the author or the
publisher endorses the information the organization or Web
site may provide or recommendations it may make. Further,
readers should be aware that Internet Web sites listed in this
work may have changed or disappeared between when this
work was written and when it is read.
For general information on our other products and services

please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at
(317) 572-3993 or fax (317) 572-4002.

13


Wiley also publishes its books in a variety of electronic
formats. Some content that appears in print may not be
available in electronic books.
Library of Congress Control Number: 2011920897
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo,
Wrox Programmer to Programmer, and related trade dress are
trademarks or registered trademarks of John Wiley & Sons,
Inc. and/or its affiliates, in the United States and other
countries, and may not be used without written permission.
WordPress is a registered trademark of Automattic, Inc. All
other trademarks are the property of their respective owners.
Wiley Publishing, Inc., is not associated with any product or
vendor mentioned in this book.

14


To my Father, Robert “Basket Bob” Williams, for inspiring
me to become the man I am today.
— Brad Williams
To my wife Ariane for her support while I was escaping
household chores, and to my kids Oscar and Cyrus who’ll be
WordPress hackers in 10 years.

— Ozh Richard
To my family for allowing me to explore the online world as
a career path and the WordPress community for inviting me
in.
— Justin Tadlock

15


CREDITS
Executive Editor
Carol Long
Project Editor
Kelly Talbot
Technical Editors
Doug Vann
Andrew Nacin
Production Editor
Rebecca Anderson
Copy Editor
Apostrophe Editing Services
Editorial Director
Robyn B. Siesky
Editorial Manager
Mary Beth Wakefield
Production Manager

16



Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Barry Pruett
Associate Publisher
Jim Minatel
Project Coordinator, Cover
Katie Crocker
Proofreader
Jen Larsen, Word One New York
Indexer
Johnna VanHoose Dinse
Cover Designer
Michael E. Trent
Cover Photo
© pagadesign/istockphoto.com

17


ABOUT THE AUTHORS
BRAD WILLIAMS is the CEO and co-founder of
WebDevStudios.com. He is also a co-host on the SitePoint
podcast and the co-author of Professional WordPress. Brad
has been developing websites for more than 14 years,
including the last 4 where he has focused on open-source
technologies like WordPress. Brad has given presentations at
various WordCamps across the country, is the organizer for
the New Jersey and Philadelphia WordPress Meetups and

WordCamp Philly. In 2010 Brad founded Pluginize.com, a
company dedicated to building custom WordPress plugins.
OZH RICHARD is a web developer who started to use
WordPress at version 1.0.1, published his first
WordPress-powered website in May 2004, and released his
first plugin three months later. He has since developed several
popular plugins, won an Annual WordPress Plugin
Competition, and is now an official judge. When not coding
WordPress plugins or sharing tutorials, Ozh contributes to
other Open Source projects such as YOURLS, a self-hosted
URL shortener, or plays Quake. You can find Ozh online at
/>JUSTIN TADLOCK is a Web developer and designer who
coded his first Web page in 2003 at the age of 18, only
months after getting his first computer. He found WordPress
in 2005 and has been working with and contributing to the
platform ever since. He has developed many popular
WordPress plugins and themes while exploring several
business paths using the open-source platform.

18


ACKNOWLEDGMENTS
THANK YOU to the love of my life, April, for your endless
support, friendship, and continuing to put up with my nerdy
ways. Thank you to my awesome nieces, Indiana Brooke and
Austin Margaret. Thank you Carol Long for believing in this
book idea and helping make it a reality. To Ozh and Justin,
two amazing co-authors, your knowledge of WordPress is
unmatched, and this book wouldn’t have been what it is

without you both. Thank you to the entire WordPress
community for your support, friendships, motivation, and
guidance. Thank you fizzypop for making WordCamp after
parties the stuff of legend. Last but not least thank you to my
ridiculous zoo: Lecter, Clarice, and Squeaks the Cat (aka
Kitty Galore). Your smiling faces and wiggly butts always put
a smile on my face.
— Brad Williams
IT’S BEEN A LONG TIME in the WordPress community
since I first started to dissect the few plugins that began to
pop like daisies in 2004 and tried to understand how things
worked. To all the coders who released the code that taught
me the innards of WordPress, I can’t express how much I owe
you. To all the members of the WordPress community who
don’t write code but foster the creativity and water our
community, thank you for your invaluable dedication. To
Brad, who sent me that crazy proposal about a plugin book, I
hope I’ll cross the oceans one day to have a few beers with
you. To Ronnie James Dio, Tom Araya, Bruce Dickinson,
Blaze Bayley, Lemmy Kilmister, Dave Mustaine, Rob
Zombie, Till Lindemann, and Mike Muir, whose gentle

19


voices have lulled me and inspired me while I was writing
late at night.
— Ozh Richard
THE WORDPRESS COMMUNITY took me in as a lost kid
who was trying to figure out life and presented me with

opportunities that I’d never dreamed possible. A simple
“thank you” is an understatement. To my plugin and theme
users, you continue to inspire me and keep my skills sharp
with your invaluable feedback and loyalty. To Brad, thank
you for that oddly random email about writing a plugin book.
To Ozh, thank you for coding all those cool plugins I learned
from before becoming a developer myself. To Granny, thank
you for allowing me to skip several dinners to work on this
book. To my family and friends, thank you for supporting me
and showing superhuman patience during hour-long
conversations (i.e., crazed rants) about plugin development.
Most importantly, to my father, who knows nothing about
Web development but taught me everything about being
successful and continues to teach me today.
— Justin Tadlock

20


FOREWORD
STARTING OUT as a simple blogging system, over the last
few years WordPress has morphed into a fully featured and
widely used content management system. It offers individuals
and companies world-wide a free and open-source alternative
to closed-source and often very expensive systems.
When I say fully featured, that’s really only true because of
the ability to add any functionality needed in the form of a
plugin. The core of WordPress is simple: You add in
functionality with plugins as you need it. Developing plugins
allows you to stand on the shoulders of a giant: You can

showcase your specific area of expertise and help users
benefit while not having to deal with parts of WordPress you
don’t care or know about.
I’ve written dozens of plugins, which together have been
downloaded millions of times. Doing that has changed my
life. It has helped me build out a business for myself, doing
development and (SEO) consultancy work. This is in your
outreach too!
I wish that when I started developing plugins for WordPress
as a hobby, some five years back, this book had been around.
It would have saved me countless hours of digging through
code and half-finished documentation. I always ended up
redoing pieces because I’d found yet another best practice or
simply an easier way of doing things.
Although this book didn’t exist yet, the authors of this book
have always been a source of good information for me while

21


developing my plugins. Each of them is an expert in his own
right; together they are one of the best teams that could have
been gathered to write this book.
WordPress makes it easy for people to have their say through
words, sound, and visuals. For those who write code,
WordPress allows you to express yourself in code. And it’s
simple. Anyone can write a WordPress plugin. With this
guide in hand, you can write a plugin that is true to
WordPress’ original vision: Code is Poetry.
Happy coding!

Joost de Valk
Yoast.com

22


INTRODUCTION
DEAR READER, thank you for picking up this book! You
have probably heard about WordPress already, the most
popular self-hosted content management system (CMS) and
blogging software in use today. WordPress powers literally
millions of Web sites on the Internet, including high profile
sites such as TechCrunch and CNN’s blog. What makes
WordPress so popular is that it’s free, open source, and
extendable beyond limits. Thanks to a powerful,
architecturally sound, and easy-to-use plugin system, you can
customize how WordPress works and extend its
functionalities. There are already more than ten thousand
plugins freely available in the official plugin repository, but
they won’t suit all your needs or client requests. That’s where
this book comes in handy!
As of this writing, we (Brad, Ozh, and Justin), have publicly
released 50 plugins, which have been downloaded nearly one
million times, and that’s not counting private client work.
This is a precious combined experience that we are going to
leverage to teach you how to code your own plugins for
WordPress by taking a hands-on approach with practical
examples and real life situations you will encounter with your
clients.
The primary reason we wanted to write this book is to create a

preeminent resource for WordPress plugin developers. When
creating plugins for WordPress, it can be a challenge to find
the resources needed in a single place. Many of the online
tutorials and guides are outdated and recommend incorrect
methods for plugin development. This book is one of the most

23


extensive collections of plugin development information to
date and should be considered required reading for anyone
wanting to explore WordPress plugin development from the
ground up.
WHO THIS BOOK IS FOR
This book is for professional Web developers who want to
make WordPress work exactly how they and their clients
want. WordPress has already proven an exceptional platform
for building any type of site from simple static pages to
networks of full-featured communities. Learning how to code
plugins will help you get the most out of WordPress and have
a cost-effective approach to developing per-client features.
This book is also for the code freelancers who want to
broaden their skill portfolio, understand the inner workings of
WordPress functionality, and take on WordPress gigs. Since
WordPress is the most popular software to code and power
websites, it is crucial that you understand how things run
under the hood and how you can make the engine work your
way. Learning how to code plugins will be a priceless asset to
add to your resume and business card.
Finally, this book is for hobbyist PHP programmers who want

to tinker with how their WordPress blog works, discover the
infinite potential of lean and flexible source code, and how
they can interact with the flow of events. The beauty of open
source is that it’s easy to learn from and easy to give back in
turn. This book will help you take your first step into a
community that will welcome your creativity and
contribution.

24


Simply put, this book is for anyone who wants to extend the
way WordPress works, whether it is for fun or profit.
WHAT YOU NEED TO USE THIS BOOK
This book assumes you already have a Web server and
WordPress running. For your convenience it is preferred that
your Web server runs on your localhost, as it will be easier to
modify plugin files as you read through the book, but an
online server is also fine.
Code snippets written in PHP are the backbone of this book:
You should be comfortable with reading and writing basic
PHP code or referring to PHP’s documentation to fill any
gaps in knowledge about fundamental functions. Advanced
PHP code tricks are explained, so you don’t need to be a PHP
expert.
You will need to have rudimentary HTML knowledge to fully
understand all the code. A basic acquaintance with database
and MySQL syntax will help with grasping advanced
subjects. To make the most of the chapter dedicated to
JavaScript and AJAX, comprehension of JavaScript code and

jQuery syntax will be a plus.
WHAT THIS BOOK COVERS
As of this writing, WordPress 3.1 is around the corner and
this book has been developed alongside this version.
Following the best coding practices outlined in this book and
using built-in APIs are keys to future-proof code that will not
be deprecated when a newer version of WordPress is released.
We believe that every code snippet in this book will still be
25


×