Creating Your First WordPress Plugin

7,478
-1

Published on

My presentation at WordCamp Philly 2011 called Creating Your First WordPress Plugin

Published in: Technology, Art & Photos
0 Comments
8 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
7,478
On Slideshare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
150
Comments
0
Likes
8
Embeds 0
No embeds

No notes for slide

Creating Your First WordPress Plugin

  1. 1. Creating Your FirstWordPress Plugin Brad Williams @williamsba
  2. 2. Who Am I?Brad WilliamsCo-Founder of WebDevStudios.comOrganizer Philly WordPress Meetup & WordCamp PhillyCo-Author of Professional WordPress (http://bit.ly/pro-wp)& Professional WordPress Plugin Development (http://amzn.to/plugindevbook) Slides available at: http://www.slideshare.net/williamsba
  3. 3. Topics What is a Plugin? Types of Plugins Sanity Practices and Plugin Foundation Determining Paths in a Plugin Activation, Deactivation, and Uninstall Methods Shortcodes, Menus, and Settings Overview Hooks: Actions and Filters Explained Resources for Plugin Developers
  4. 4. What is a Plugin? A plugin in WordPress is a PHP script that extends, or alters, the core functionality of WordPress.Quite simply plugins are files installed in WordPress to add a feature, or set of features, to WordPress.
  5. 5. What is a Plugin?http://wordpress.org/extend/plugins/
  6. 6. Types and Statuses of Plugins Active – Plugin is active and running in WordPress Inactive – Plugin is installed but not active. No code from the plugin is executed Must-Use – All plugins installed in wp-content/mu-plugins. All plugins are loaded automatically. Only way to deactivate is to remove. Drop-ins – Core functionality of WordPress can be replaced by Drop-in plugins.  advanced-cache-php – Advanced caching plugin  db.php – Custom database class  maintenance.php – Custom maintenance message  sunrise.php – Domain mapping  And more…
  7. 7. Plugin Header Requirements <?php /* Plugin Name: WordCamp Philly 2011 Plugin URI: http://webdevstudios.com/support/wordpress-plugins/ Description: Plugin for WordCamp Philly Version: 1.0 Author: Brad Williams Author URI: http://webdevstudios.com */ ?>Plugin is now available to beactivated in WordPress!
  8. 8. Sanity PracticesPrefix Everything!update_option() //BAD FUNCTION NAME bw_wcphilly_update_option() //GOOD FUNCTION NAME! $settings //BAD VARIABLE NAME $bw_wcphilly_settings //GOOD VARIABLE NAME! Organized Folder Structure • /unique-plugin-name • unique-plugin-name.php Keeping your files organized • uninstall.php using a clean folder structure • /js can make it much easier to • /css track the flow of your plugin over • /includes time. • /images
  9. 9. Determining PathsLocal Paths<?php//display local path to my plugin directoryecho plugin_dir_path( __FILE__ );?>Would display: /public_html/wp-content/plugins/my-new-plugin/<?php//display local path to my includes/functions.php fileecho plugin_dir_path( __FILE__ ) .‟includes/functions.php‟;?>Would display: /public_html/wp-content/plugins/my-new-plugin/includes/functions.php __FILE__ is a “magical” PHP constant containing the full path and filename of the file
  10. 10. Determining PathsURL Paths<?php//display the URL to images/icon.pngecho plugins_url( images/icon.png, __FILE__ );?>Would display: http://example.com/wp-content/plugins/my-new-plugin/images/icon.png Advantages of plugins_url() • Supports the mu-plugins directory • Auto detects SSL, so if enabled the URL would return https • Uses the WP_PLUGIN_URL constant, meaning it can detect the correct path even if /wp-content has been moved • Supports Multisite using the WPMU_PLUGIN_URL constant
  11. 11. Important TechniquesPlugin Activation Function<?phpregister_activation_hook( __FILE__, bw_wcphilly_install );function bw_wcphilly_install() { if ( version_compare( get_bloginfo( version ), „4.0, < ) ) { deactivate_plugins( plugin_basename( __FILE__ ) ); // Deactivate our plugin wp_die( This plugin requires WordPress version 4.0 or higher. ); }}?> register_activation_hook( $file, $function ) Parameters: • $file (string) (required) – Path to the primary plugin file • $function (string) (required) – Function to be executed when plugin is activated http://codex.wordpress.org/Function_Reference/register_activation_hook
  12. 12. Important TechniquesPlugin Deactivation Function<?phpregister_deactivation_hook( __FILE__, bw_wcphilly_deactivate );function bw_wcphilly_deactivate() { //do stuff}?> register_deactivation_hook( $file, $function ) Parameters: • $file (string) (required) – Path to the primary plugin file • $function (string) (required) – Function to be executed when plugin is deactivated REMEMBER: Deactivating is NOT uninstalling. Always assume your users will reactivate at a later date. http://codex.wordpress.org/Function_Reference/register_deactivation_hook
  13. 13. Important TechniquesPlugin Uninstall 1. Create a uninstall.php file in the root directory of your plugin 2. Add all uninstall code to this file<?phpif( !defined( WP_UNINSTALL_PLUGIN ) ) exit ();// Delete option from options tabledelete_option( „bw_wcphilly_options );?> If the WP_UNINSTALL_PLUGIN constant is not defined we know WordPress did not call this file. This is a security measure in WordPress Uninstall.php is the recommended uninstall method, but there is another method called register_uninstall_hook() http://jacobsantos.com/2008/general/wordpress-27-plugin-uninstall-methods/
  14. 14. What is a Hook? Hooks enable plugin developers to “hook” into WordPress and change how it works without modifying the core codeThere are two kinds of hooks: Actions and Filtershttp://jacobsantos.com/2008/general/wordpress-27-plugin-uninstall-methods/
  15. 15. Hooks Action HooksEnables you to execute a function at specific points in the WordPress loading process<?phpadd_action( user_register, bw_wcphilly_welcome_email );function bw_wcphilly_welcome_email( $user_id ) { $user_info = get_userdata( $user_id ); //populate email values $email_to = is_email( $user_info->user_email ); $email_subject = Welcome!; $email_msg = Thank you for registering on my website!; //send welcome email wp_mail( $email_to, $email_subject, $email_msg );}?> http://codex.wordpress.org/Plugin_API/Action_Reference
  16. 16. HooksCommon Action Hooks • plugins_loaded – Earliest hook in the WP loading process, after all plugins have been loaded • init – Fire after most of WP is set up so all information is available admin_menu – Runs when the basic admin menu structure is in place • template_redirect – Executed just before the theme template is chosen • wp_head – Executed on the front end of WordPress between the <head> tags • wp_footer – Runs in the footer of your theme • admin_head – Executed on the admin side of WordPress between the <head> tags • admin_footer – Runs in the footer of the admin side of WordPress • user_register – Executes when a new user account is created • save_post – Runs when a post or page is created or updated http://codex.wordpress.org/Plugin_API/Action_Reference
  17. 17. HooksFilter Hooks Enables you to manipulate the output of code and content in WordPress<?phpadd_filter( the_content, bw_wcphilly_filter_content );function bw_wcphilly_filter_content( $text ) { $text = str_replace( Drupal, WordPress, $text ); return $text;}?> Change every instance of Drupal to WordPress in your content >:) REMEMBER: Using a filter does NOT change the content in the database, it simply alters it prior to displaying http://codex.wordpress.org/Plugin_API/Filter_Reference
  18. 18. HooksFilter Hooks<?phpadd_filter ( the_content, „bw_wcphilly_insertFootNote );function bw_wcphilly_insertFootNote( $content ) { if( !is_feed() && !is_home() ) { $content .= "<div class=subscribe>"; $content .= "<h4>Enjoyed this article?</h4>"; $content .= "<p>Subscribe to my <a href=http://feeds2.feedburner.com/strangework>RSSfeed</a>!</p>"; $content .= "</div>"; } return $content;}?> http://codex.wordpress.org/Plugin_API/Filter_Reference
  19. 19. HooksCommon Filter Hooks • the_content – Filter applied to the content of the post or page • the_title – Applied to the post title • body_class – Applied to the <body> tag class parameter • default_content – Applied to the content on a new post or page • comment_text – Applied to the comment text of a comment http://codex.wordpress.org/Plugin_API/Filter_Reference
  20. 20. HooksNumber of Hooks in WordPress by Version http://adambrown.info/p/wp_hooks
  21. 21. Plugin FoundationIt‟s important to start with a solid foundation
  22. 22. Plugin FoundationExample Plugin Foundation<?php/*Plugin Name: WordCamp PhillyPlugin URI: http://webdevstudios.com/support/wordpress-plugins/Description: Plugin for WordCamp PhillyVersion: 1.0Author: Brad WilliamsAuthor URI: http://webdevstudios.comLicense: GPLv2*/// DEFINE CONSTANTSdefine( „WCPHILLY_VERSION, 1.0 );define( WCPHILLY_TEXTDOMAIN, „wcphilly_plugin );define( WCPHILLY_BASENAME, plugin_basename(__FILE__) );define( WCPHILLY_DIR, plugin_dir_path( __FILE__ ) );define( WCPHILLY_URL, plugins_url( my-new-plugin/ ) );require_once( WCPHILLY_DIR . includes/core.php );?>
  23. 23. Shortcode ExampleExample<?php// Register a new shortcode: [book]add_shortcode( book, bw_wcphilly_book );// The callback function that will replace [book]function bw_wcphilly_book() { return <a href="http://amzn.to/plugindevbook">Professional WordPress PluginDevelopment</a>;}?>
  24. 24. Menu Example Example Custom Menu<?phpadd_action( admin_menu, bw_wcphilly_create_menu );function bw_wcphilly_create_menu() { //create custom top-level menu add_menu_page(WC Philly Settings Page, WC Philly, manage_options, wcphilly-plugin, bw_wcphilly_settings_page ); //create submenu items add_submenu_page( wcphilly-plugin, About My Plugin, About, manage_options, wcphilly-plugin_about, bw_wcphilly_about_page ); add_submenu_page( wcphilly-plugin, Help with My Plugin, Help, manage_options, wcphilly-plugin_help, bw_wcphilly_help_page ); add_submenu_page( wcphilly-plugin, Uinstall My Plugin, Uninstall, manage_options, nyc-meetup-plugin_uninstall, bw_wcphilly_uninstall_page );}?>
  25. 25. Menu Exampleadd_menu_page()Parameters:$page_title – The title tag text$menu_title – The menu name$capability - Capability required to view menu$menu_slug – Unique slug to reference menu by$function – Function that displays the pages content$icon_url – URL for a custom menu icon$position – Position the menu should appearadd_submenu_page()Parameters:$parent_slug – Slug name for the parent menu$page_title – The title tag text$menu_title – The submenu name$capability – Capability required to view submenu$menu_slug – Unique slug to reference menu by$function – Function that displays the pages content
  26. 26. Menu ExampleAdd Submenu to Custom Post Type<?phpadd_action( admin_menu, bw_wcphilly_create_menu );function bw_wcphilly_create_menu() {//create submenu itemsadd_submenu_page( edit.php?post_type=movies, About My Plugin, About, manage_options, „wcphilly-plugin_about, bw_wcphilly_about_page );}?> You can easily add a submenu to any Custom Post Type menu by setting the $parent_slug to edit.php?post_type=POSTTYPENAME
  27. 27. Menu ExampleAdd Submenu to Existing Menu<?phpadd_action( admin_menu, bw_wcphilly_create_menu );function bw_wcphilly_create_menu() {//create Settings submenu page add_options_page(WC Philly Settings Page, WC Philly, manage_options,wcphilly-plugin, bw_wcphilly_settings_page );}function bw_wcphilly_settings_page() { //settings page}?>
  28. 28. Menu Exampleadd_options_page()Parameters:$page_title – The title tag text$menu_title – The menu name$capability - Capability required to view menu$menu_slug – Unique slug to reference menu by$function – Function that displays the pages content add_dashboard_page() add_posts_page() add_media_page() add_links_page() add_pages_page() add_comments_page() add_theme_page() add_plugins_page() add_users_page() add_management_page() add_options_page()
  29. 29. Plugin Developer Resources Official Resources › WordPress Core! › http://wordpress.org/extend/plugins/ › http://codex.wordpress.org/Writing_a_Plugin › http://codex.wordpress.org/Data_Validation › http://wordpress.org/support/forum/hacks › http://lists.automattic.com/mailman/listinfo/wp-hackers › http://codex.wordpress.org/IRC ( #wordpress channel ) › http://wpdevel.wordpress.com/ › http://wordpress.org/extend/ideas/ Developer Websites › http://wpengineer.com › http://phpxref.ftwr.co.uk/wordpress/ › http://adambrown.info/p/wp_hooks
  30. 30. ContactBrad Williamsbrad@webdevstudios.comBlog: strangework.comTwitter: @williamsbaIRC: WDS-Brad http://www.slideshare.net/williamsba
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×