SlideShare una empresa de Scribd logo
1 de 39
PHP WordPressCustomizationWordCamp Miami 2011 Take the Good Parts, Then Bend It To Your Will By David F. Carr david@carrcommunications.com
Self Introduction Freelance writer, editor, and web consultant Write for Forbes.com on cloud computing, technology for small to midsize businesses Technology Editor for WebWeek / Internet World Magazine in1990s, Baseline Magazine 2001-2008 Webmaster for small businesses, community organizations, political campaigns WordPress replaced a lot of custom hacks Will mostly be talking about plugins to modify the behavior of the system
Overview Why start with WordPress? A Plugin Is Just PHP, a Theme Is PHP/CSS JavaScript / AJAX, too Files, system load, and The Loop Hooking into Filters and Actions Customizing the admin screens Customizing the front end Creating a custom post type Where to learn more
When a Plugin Makes You Popular
Why Start With WordPress? Faster than starting from a clean sheet of paper (blank screen of code) Content management for blogs, web pages SEO friendly Availability of vast array of free themes and plugins, plus commercial options Lots of tutorial material Strong developer community
A Plugin Is Just PHP
Anatomy of a Theme Themes have a similar header in style.css. Theme loads index.php (or page.php, single.php, archive.php) to execute “the loop.” Each also loads header.php, footer.php, and usually sidebar.php
The Loop
Globals and Lookup Functions site_url() admin_url() content_url() or WP_CONTENT_URL plugins_url() or WP_PLUGIN_URL includes_url() home_url() WP_PLUGIN_DIR WP_CONTENT_DIR ABSPATH – directory including trailing / None of the rest include trailing / So $url = plugins_url() . /demo/report.php
More Globals, Conditional Functions Need to use global keyword at top of function to access global $wpdb – database object global $post $post-ID, $post->post_type global $current_user $current_user->first_name Conditional functions is_user_logged_in() is_single() or is_single(10) is_page or is_page(10) or is_page('about_us') is_admin() – is this an admin page?
WordPress File Hierarchy The wp-content directory has subdirectories for plugins and themes The index.php in web root loads the system, loads activatedplugins and themes Plugins: functionality Themes: look and feel functions.php – theme-specific behavior
Hooking Into WordPress Core WordPress API built around 2 kinds of hooks: Filter hooks – intercept some bit of content, modify it, return it. Mostly UI but also some back end filters. A filter on ‘the content’ modifies the content of a post. A filter on ‘posts_orderby’ modifies the ORDER BY clause in the SQL for retrieving posts. Action hooks – triggered by an event in WordPress initialization or loading of template files. The ‘init’ action comes after database is loaded but before page display starts. Can be used to act on a $_POST, then redirect. The ‘wp_header’ and ‘wp_footer’ actions called from header.php and footer.php output custom content Other actions specific to admin screens, like ‘admin_menu’
Key Actions Public Page muplugins_loaded plugins_loaded setup_theme load_textdomain set_current_user init wp_loaded parse_request send_headers parse_query pre_get_posts posts_selection wp template_redirect wp_head wp_enqueue_scripts wp_print_styles wp_print_scripts loop_start the_post loop_end get_sidebar wp_footer wp_print_footer_scripts shutdown
Sample Filters wp_title (page title) the_title (post title) the_content the_content_feed the_excerpt the_excerpt_rss the_category the_tags the_time the_date the_weekday comment_text comment_save_pre the_editor_content wp_list_pages save_post wp_insert_post_data login_redirect cron_schedules mce_css (rich text editor) posts_request posts_join posts_orderby posts_where
Modifying Admin Screens The Default Dashboard
Custom Dashboard
Custom Admin Menus
Function to output menu page
Admin Data Entry Page
Nonce Security Number used once Make sure requests coming from authenticated user with unique code $nonce= wp_create_nonce ('my-nonce'); wp_nonce_field("qday","qnonce") is the same as:<input type=“text” name=“qnonce” value=“<?=$nonce?>”> Test: Code: if(wp_verify_nonce($_POST["qnonce"], "qday") )
Catching $_POST at init / admin-init
Process, Then Redirect Separate UI from server processing Helps avoid double-submit issues Redirect with different parameters for success / failure Exit after redirect Similar pattern can be used for AJAX (echo json, then exit)
Wrapper Functions For WP Database Create a post with code using wp_insert_post Retrieve and change settings using get_option and update_option
Settings API
The WordPress Database
Database Programming with WordPress Global $wpdb data access object Get results with $wpdb->get_results Get row with $wpdb->get_row Format/quote SQL with $wpdb->prepare
Insert / Update	 Remember security Check nonce Filter values Compensate for “magic quotes” with$postdata = array_map( 'stripslashes_deep', $_POST ); Use $wpdb->prepare to quote properly Execute insert / update with $wpdb->query($sql)
DB Programming Pitfalls Forgetting to declare $wpdb as global Use ARRAY_A parameter to get associative array from $wpdb->get_results or $wpdb->get_row if you want results to be accessible as $row["field_name"] Default is object format $row->field_name Use $wpdb->show_errors() to debug SQL Return value from $wpdb->query is false on error, or number of rows affected (could be 0) Test for error: if($return_value == false) echo ‘error’;
Allow For Alternate Table Names Default table names like wp_posts can have alternate prefixes, so use $wpdb->posts instead Custom table $wpdb->prefix . "rsvpmaker"
Shortcodes Placeholder codes site editors can include in pages and posts Standard:[embed] http://www.youtube.com/watch?v=nTDNLUzjkpg[/embed] Custom:[demotag title="Date" date="r"] Date in RFC822 Format [/demotag]
Contact Form Example Use a shortcode to display form Process $_POST on ‘init’ then redirect Use JavaScript jQuery library to enhance
Enqueue Bundled / Custom JavaScript Load scripts in right order with wp_enqueue_script Register custom scripts, dependencies with wp_register_script
jQuery and Friends “No Conflict” mode so start with jQuery(document).ready(function($) Warning: Textbook jQuery examples usually start with this shortcut: $(document).ready(function()
Live Example - RSVPMaker
Creating a Custom Post Type Add a content type that can use common editing controls but be organized separately
Editing Screen With Custom Options Standard formatting / uploading controls Custom panels: add_meta_box Process $_POST on save_post action Save custom data: update_post_meta
Custom Display for Custom Post Type Filter ‘the_content’, check post type, look up and format dates for events, display form if is_single() otherwise show RSVP Now! button
Summary WordPress provides a foundation / framework Create / customize themes to change look and feel Download or create your own plugins to alter WordPress system behavior Filters hooks alter content, return results Action hooks triggered by initialization stages, function calls in theme templates, administration screen access Create your own administration reports / data entry screens. Use wrapper functions and $wpdb global to update DB Use shortcodes, filters, output functions for JavaScript and CSS to enhance public website
Follow Up Email: david@carrcommunications.com Recommended book:WordPressPlugin Development – Beginner’s Guide by Vladimir Prelovac Presentation/Code/Links:www.carrcommunications.com/wordcamp/www.carrcommunications.com/wordpress-plugins/ Developer documentation codex.wordpress.org Forums wordpress.org/support/ Mailing lists (wp-hackers etc.) lists.automattic.com

Más contenido relacionado

La actualidad más candente

Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress DeveloperJoey Kudish
 
WordPress Theme Development: Part 2
WordPress Theme Development: Part 2WordPress Theme Development: Part 2
WordPress Theme Development: Part 2Josh Lee
 
WordPress as the Backbone(.js)
WordPress as the Backbone(.js)WordPress as the Backbone(.js)
WordPress as the Backbone(.js)Beau Lebens
 
Custom Post Types in Depth at WordCamp Montreal
Custom Post Types in Depth at WordCamp MontrealCustom Post Types in Depth at WordCamp Montreal
Custom Post Types in Depth at WordCamp MontrealJoey Kudish
 
Alchemy CMS: First User Group (Berlin)
Alchemy CMS: First User Group (Berlin)Alchemy CMS: First User Group (Berlin)
Alchemy CMS: First User Group (Berlin)Moritz Scholz
 
Working with the django admin
Working with the django admin Working with the django admin
Working with the django admin flywindy
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Paul Bearne
 
Put a little Backbone in your WordPress
Put a little Backbone in your WordPressPut a little Backbone in your WordPress
Put a little Backbone in your WordPressadamsilverstein
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with FlaskMake School
 
Associations & JavaScript
Associations & JavaScriptAssociations & JavaScript
Associations & JavaScriptJoost Elfering
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP frameworkDinh Pham
 
Understanding JSP -Servlets
Understanding JSP -ServletsUnderstanding JSP -Servlets
Understanding JSP -ServletsGagandeep Singh
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSAntonio Peric-Mazar
 
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)Clément Wehrung
 
Advanced WordPress Development Environments
Advanced WordPress Development EnvironmentsAdvanced WordPress Development Environments
Advanced WordPress Development EnvironmentsBeau Lebens
 
Java One Presentation - Ruby on Rails meets Enterprise
Java One Presentation - Ruby on Rails meets EnterpriseJava One Presentation - Ruby on Rails meets Enterprise
Java One Presentation - Ruby on Rails meets Enterprisedan_mcweeney
 
Ruby on Rails Meets Enterprise Applications
Ruby on Rails Meets Enterprise ApplicationsRuby on Rails Meets Enterprise Applications
Ruby on Rails Meets Enterprise Applicationsdan_mcweeney
 
HTML 5 Step By Step - Ebook
HTML 5 Step By Step - EbookHTML 5 Step By Step - Ebook
HTML 5 Step By Step - EbookScottperrone
 

La actualidad más candente (20)

Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
 
WordPress Theme Development: Part 2
WordPress Theme Development: Part 2WordPress Theme Development: Part 2
WordPress Theme Development: Part 2
 
WordPress as the Backbone(.js)
WordPress as the Backbone(.js)WordPress as the Backbone(.js)
WordPress as the Backbone(.js)
 
Custom Post Types in Depth at WordCamp Montreal
Custom Post Types in Depth at WordCamp MontrealCustom Post Types in Depth at WordCamp Montreal
Custom Post Types in Depth at WordCamp Montreal
 
Alchemy CMS: First User Group (Berlin)
Alchemy CMS: First User Group (Berlin)Alchemy CMS: First User Group (Berlin)
Alchemy CMS: First User Group (Berlin)
 
Working with the django admin
Working with the django admin Working with the django admin
Working with the django admin
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
 
Put a little Backbone in your WordPress
Put a little Backbone in your WordPressPut a little Backbone in your WordPress
Put a little Backbone in your WordPress
 
19servlets
19servlets19servlets
19servlets
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
 
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component DevelopmentEVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
 
Associations & JavaScript
Associations & JavaScriptAssociations & JavaScript
Associations & JavaScript
 
How to learn to build your own PHP framework
How to learn to build your own PHP frameworkHow to learn to build your own PHP framework
How to learn to build your own PHP framework
 
Understanding JSP -Servlets
Understanding JSP -ServletsUnderstanding JSP -Servlets
Understanding JSP -Servlets
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
 
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
ePub 3, HTML 5 & CSS 3 (+ Fixed-Layout)
 
Advanced WordPress Development Environments
Advanced WordPress Development EnvironmentsAdvanced WordPress Development Environments
Advanced WordPress Development Environments
 
Java One Presentation - Ruby on Rails meets Enterprise
Java One Presentation - Ruby on Rails meets EnterpriseJava One Presentation - Ruby on Rails meets Enterprise
Java One Presentation - Ruby on Rails meets Enterprise
 
Ruby on Rails Meets Enterprise Applications
Ruby on Rails Meets Enterprise ApplicationsRuby on Rails Meets Enterprise Applications
Ruby on Rails Meets Enterprise Applications
 
HTML 5 Step By Step - Ebook
HTML 5 Step By Step - EbookHTML 5 Step By Step - Ebook
HTML 5 Step By Step - Ebook
 

Similar a Introduction to Plugin Programming, WordCamp Miami 2011

WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practicesmarkparolisi
 
Getting Started With WordPress Development
Getting Started With WordPress DevelopmentGetting Started With WordPress Development
Getting Started With WordPress DevelopmentAndy Brudtkuhl
 
Getting started with WordPress development
Getting started with WordPress developmentGetting started with WordPress development
Getting started with WordPress developmentSteve Mortiboy
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress DevelopmentAdam Tomat
 
So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017
So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017 So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017
So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017 Evan Mullins
 
Mastering WordPress Vol.1
Mastering WordPress Vol.1Mastering WordPress Vol.1
Mastering WordPress Vol.1Wataru OKAMOTO
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
WordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big wordsWordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big wordsTomAuger
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfonyFrancois Zaninotto
 
The Way to Theme Enlightenment
The Way to Theme EnlightenmentThe Way to Theme Enlightenment
The Way to Theme EnlightenmentAmanda Giles
 
How To Write a WordPress Plugin
How To Write a WordPress PluginHow To Write a WordPress Plugin
How To Write a WordPress PluginAndy Stratton
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management SystemValent Mustamin
 
Intro to WordPress Plugin Development
Intro to WordPress Plugin DevelopmentIntro to WordPress Plugin Development
Intro to WordPress Plugin DevelopmentBrad Williams
 
Writing your own WordPress themes and plugins
Writing your own WordPress themes and pluginsWriting your own WordPress themes and plugins
Writing your own WordPress themes and pluginsStephanie Wells
 
Plugin Development Practices
Plugin Development PracticesPlugin Development Practices
Plugin Development Practicesdanpastori
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Bending word press to your will
Bending word press to your willBending word press to your will
Bending word press to your willTom Jenkins
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress WebsitesKyle Cearley
 
Creating Your First WordPress Plugin
Creating Your First WordPress PluginCreating Your First WordPress Plugin
Creating Your First WordPress PluginBrad Williams
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolmentRajib Ahmed
 

Similar a Introduction to Plugin Programming, WordCamp Miami 2011 (20)

WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practices
 
Getting Started With WordPress Development
Getting Started With WordPress DevelopmentGetting Started With WordPress Development
Getting Started With WordPress Development
 
Getting started with WordPress development
Getting started with WordPress developmentGetting started with WordPress development
Getting started with WordPress development
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017
So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017 So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017
So, You Wanna Dev? Join the Team! - WordCamp Raleigh 2017
 
Mastering WordPress Vol.1
Mastering WordPress Vol.1Mastering WordPress Vol.1
Mastering WordPress Vol.1
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
WordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big wordsWordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big words
 
Simplify your professional web development with symfony
Simplify your professional web development with symfonySimplify your professional web development with symfony
Simplify your professional web development with symfony
 
The Way to Theme Enlightenment
The Way to Theme EnlightenmentThe Way to Theme Enlightenment
The Way to Theme Enlightenment
 
How To Write a WordPress Plugin
How To Write a WordPress PluginHow To Write a WordPress Plugin
How To Write a WordPress Plugin
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management System
 
Intro to WordPress Plugin Development
Intro to WordPress Plugin DevelopmentIntro to WordPress Plugin Development
Intro to WordPress Plugin Development
 
Writing your own WordPress themes and plugins
Writing your own WordPress themes and pluginsWriting your own WordPress themes and plugins
Writing your own WordPress themes and plugins
 
Plugin Development Practices
Plugin Development PracticesPlugin Development Practices
Plugin Development Practices
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Bending word press to your will
Bending word press to your willBending word press to your will
Bending word press to your will
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress Websites
 
Creating Your First WordPress Plugin
Creating Your First WordPress PluginCreating Your First WordPress Plugin
Creating Your First WordPress Plugin
 
Starting with PHP and Web devepolment
Starting with PHP and Web devepolmentStarting with PHP and Web devepolment
Starting with PHP and Web devepolment
 

Último

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Último (20)

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

Introduction to Plugin Programming, WordCamp Miami 2011

  • 1. PHP WordPressCustomizationWordCamp Miami 2011 Take the Good Parts, Then Bend It To Your Will By David F. Carr david@carrcommunications.com
  • 2. Self Introduction Freelance writer, editor, and web consultant Write for Forbes.com on cloud computing, technology for small to midsize businesses Technology Editor for WebWeek / Internet World Magazine in1990s, Baseline Magazine 2001-2008 Webmaster for small businesses, community organizations, political campaigns WordPress replaced a lot of custom hacks Will mostly be talking about plugins to modify the behavior of the system
  • 3. Overview Why start with WordPress? A Plugin Is Just PHP, a Theme Is PHP/CSS JavaScript / AJAX, too Files, system load, and The Loop Hooking into Filters and Actions Customizing the admin screens Customizing the front end Creating a custom post type Where to learn more
  • 4. When a Plugin Makes You Popular
  • 5. Why Start With WordPress? Faster than starting from a clean sheet of paper (blank screen of code) Content management for blogs, web pages SEO friendly Availability of vast array of free themes and plugins, plus commercial options Lots of tutorial material Strong developer community
  • 6. A Plugin Is Just PHP
  • 7. Anatomy of a Theme Themes have a similar header in style.css. Theme loads index.php (or page.php, single.php, archive.php) to execute “the loop.” Each also loads header.php, footer.php, and usually sidebar.php
  • 9. Globals and Lookup Functions site_url() admin_url() content_url() or WP_CONTENT_URL plugins_url() or WP_PLUGIN_URL includes_url() home_url() WP_PLUGIN_DIR WP_CONTENT_DIR ABSPATH – directory including trailing / None of the rest include trailing / So $url = plugins_url() . /demo/report.php
  • 10. More Globals, Conditional Functions Need to use global keyword at top of function to access global $wpdb – database object global $post $post-ID, $post->post_type global $current_user $current_user->first_name Conditional functions is_user_logged_in() is_single() or is_single(10) is_page or is_page(10) or is_page('about_us') is_admin() – is this an admin page?
  • 11. WordPress File Hierarchy The wp-content directory has subdirectories for plugins and themes The index.php in web root loads the system, loads activatedplugins and themes Plugins: functionality Themes: look and feel functions.php – theme-specific behavior
  • 12. Hooking Into WordPress Core WordPress API built around 2 kinds of hooks: Filter hooks – intercept some bit of content, modify it, return it. Mostly UI but also some back end filters. A filter on ‘the content’ modifies the content of a post. A filter on ‘posts_orderby’ modifies the ORDER BY clause in the SQL for retrieving posts. Action hooks – triggered by an event in WordPress initialization or loading of template files. The ‘init’ action comes after database is loaded but before page display starts. Can be used to act on a $_POST, then redirect. The ‘wp_header’ and ‘wp_footer’ actions called from header.php and footer.php output custom content Other actions specific to admin screens, like ‘admin_menu’
  • 13. Key Actions Public Page muplugins_loaded plugins_loaded setup_theme load_textdomain set_current_user init wp_loaded parse_request send_headers parse_query pre_get_posts posts_selection wp template_redirect wp_head wp_enqueue_scripts wp_print_styles wp_print_scripts loop_start the_post loop_end get_sidebar wp_footer wp_print_footer_scripts shutdown
  • 14. Sample Filters wp_title (page title) the_title (post title) the_content the_content_feed the_excerpt the_excerpt_rss the_category the_tags the_time the_date the_weekday comment_text comment_save_pre the_editor_content wp_list_pages save_post wp_insert_post_data login_redirect cron_schedules mce_css (rich text editor) posts_request posts_join posts_orderby posts_where
  • 15. Modifying Admin Screens The Default Dashboard
  • 18. Function to output menu page
  • 20. Nonce Security Number used once Make sure requests coming from authenticated user with unique code $nonce= wp_create_nonce ('my-nonce'); wp_nonce_field("qday","qnonce") is the same as:<input type=“text” name=“qnonce” value=“<?=$nonce?>”> Test: Code: if(wp_verify_nonce($_POST["qnonce"], "qday") )
  • 21. Catching $_POST at init / admin-init
  • 22. Process, Then Redirect Separate UI from server processing Helps avoid double-submit issues Redirect with different parameters for success / failure Exit after redirect Similar pattern can be used for AJAX (echo json, then exit)
  • 23. Wrapper Functions For WP Database Create a post with code using wp_insert_post Retrieve and change settings using get_option and update_option
  • 26. Database Programming with WordPress Global $wpdb data access object Get results with $wpdb->get_results Get row with $wpdb->get_row Format/quote SQL with $wpdb->prepare
  • 27. Insert / Update Remember security Check nonce Filter values Compensate for “magic quotes” with$postdata = array_map( 'stripslashes_deep', $_POST ); Use $wpdb->prepare to quote properly Execute insert / update with $wpdb->query($sql)
  • 28. DB Programming Pitfalls Forgetting to declare $wpdb as global Use ARRAY_A parameter to get associative array from $wpdb->get_results or $wpdb->get_row if you want results to be accessible as $row["field_name"] Default is object format $row->field_name Use $wpdb->show_errors() to debug SQL Return value from $wpdb->query is false on error, or number of rows affected (could be 0) Test for error: if($return_value == false) echo ‘error’;
  • 29. Allow For Alternate Table Names Default table names like wp_posts can have alternate prefixes, so use $wpdb->posts instead Custom table $wpdb->prefix . "rsvpmaker"
  • 30. Shortcodes Placeholder codes site editors can include in pages and posts Standard:[embed] http://www.youtube.com/watch?v=nTDNLUzjkpg[/embed] Custom:[demotag title="Date" date="r"] Date in RFC822 Format [/demotag]
  • 31. Contact Form Example Use a shortcode to display form Process $_POST on ‘init’ then redirect Use JavaScript jQuery library to enhance
  • 32. Enqueue Bundled / Custom JavaScript Load scripts in right order with wp_enqueue_script Register custom scripts, dependencies with wp_register_script
  • 33. jQuery and Friends “No Conflict” mode so start with jQuery(document).ready(function($) Warning: Textbook jQuery examples usually start with this shortcut: $(document).ready(function()
  • 34. Live Example - RSVPMaker
  • 35. Creating a Custom Post Type Add a content type that can use common editing controls but be organized separately
  • 36. Editing Screen With Custom Options Standard formatting / uploading controls Custom panels: add_meta_box Process $_POST on save_post action Save custom data: update_post_meta
  • 37. Custom Display for Custom Post Type Filter ‘the_content’, check post type, look up and format dates for events, display form if is_single() otherwise show RSVP Now! button
  • 38. Summary WordPress provides a foundation / framework Create / customize themes to change look and feel Download or create your own plugins to alter WordPress system behavior Filters hooks alter content, return results Action hooks triggered by initialization stages, function calls in theme templates, administration screen access Create your own administration reports / data entry screens. Use wrapper functions and $wpdb global to update DB Use shortcodes, filters, output functions for JavaScript and CSS to enhance public website
  • 39. Follow Up Email: david@carrcommunications.com Recommended book:WordPressPlugin Development – Beginner’s Guide by Vladimir Prelovac Presentation/Code/Links:www.carrcommunications.com/wordcamp/www.carrcommunications.com/wordpress-plugins/ Developer documentation codex.wordpress.org Forums wordpress.org/support/ Mailing lists (wp-hackers etc.) lists.automattic.com