SlideShare a Scribd company logo
Yannick Lefebvre
@ylefebvre
ylefebvre.ca
WordPress Plugin Developer / Author
Plugin Development Demystified
Second Edition
Topics
●
Plugins Overview
●
Types of plugin developers
●
Plugins vs functions.php
●
File Structure
●
Required Tools
●
Plugin file header
●
Turning functions.php code
into a plugin
●
Actions hook
●
Filter hook
●
Shortcodes
●
More tools
●
Considerations
●
Publishing your plugin
●
Recommended Readings
●
Questions
Plugin Development Demystified
Slides at ylefebvre.ca/wcmtl2017
About me
●
WordPress user since 2004
●
Released first plugin in 2005
●
8 plugins on oficial repository
●
Author of WordPress Plugin
Development Cookbook, Second
Edition
– Use code WPDCSEd50 to get
50% of eBook on
packtpub.com until Sept 12
●
Custom plugin development
Slides at ylefebvre.ca/wcmtl2017
Plugins Overview
●
Extend WordPress capabilities
●
Open plugin architecture
●
Ofer function of varying complexity
●
More than 50,000 plugins available today!
Plugins Overview
●
Extend WordPress capabilities
●
Open plugin architecture
●
Ofer function of varying complexity
●
More than 50,000 plugins available today!
Who makes
these plugins
and what
tools do they
use to make
them?
Types of plugin developers
Site administrator Website developer
Community developerFreelance developer
Plugins vs functions.php
●
Ever written your own plugin?
Plugins vs functions.php
●
Ever written your own plugin?
●
Ever added code to functions.php on your own site or in a
customer project?
function ylefebvre_add_favicon(){ ?>
<link rel="shortcut icon" href="<?php echo
get_stylesheet_directory_uri(); ?>/images/favicon.ico"/>
<?php }
add_action( 'wp_head', 'ylefebvre_add_favicon' );
function ylefebvre_add_favicon(){ ?>
<link rel="shortcut icon" href="<?php echo
get_stylesheet_directory_uri(); ?>/images/favicon.ico"/>
<?php }
add_action( 'wp_head', 'ylefebvre_add_favicon' );
Plugins vs functions.php
●
Ever written your own plugin?
functions.php code is 99%of the way towards making a
plugin with 0%of the benefits
●
Ever added code to functions.php on your own site or in a
customer project?
function ylefebvre_add_favicon(){ ?>
<link rel="shortcut icon" href="<?php echo
get_stylesheet_directory_uri(); ?>/images/favicon.ico"/>
<?php }
add_action( 'wp_head', 'ylefebvre_add_favicon' );
function ylefebvre_add_favicon(){ ?>
<link rel="shortcut icon" href="<?php echo
get_stylesheet_directory_uri(); ?>/images/favicon.ico"/>
<?php }
add_action( 'wp_head', 'ylefebvre_add_favicon' );
Plugins vs functions.php
Benefit functions.php Plugin
Easily activated or deactivated
without need to search or risk of
afecting other code
Theme-independent
Easy to update in customer
installations
Basic Plugin File Structure
●
One or more plain text php code file(s)
●
Can contain other file types (e.g. images,
text files, translation files, etc…)
●
Distributed as zip file
Required Tools
Required
●
Text Editor (Notepad)
Required Tools
Optional
●
Code editor (e.g. Notepad++, Programmer’s
Notepad, Sublime Text)
Required Tools
Optional
●
CodeIDE (PhpStorm)
Required Tools
Optional
●
Image Editor
●
Local web server
– VVV – Varying Vagrant Vagrants
– XAMPP
– MAMP
– WSL – Windows Subsystem for Linux)
●
Archive Tool
Plugin File Header
<?php
/*
Plugin Name: My New Google Analytics Plugin
Plugin URI: http://ylefebvre.ca
Description: New revolutionary GA Plugin
Version: 1.0
Author: Yannick Lefebvre
Author URI: http://ylefebvre.ca
License: GPL2
*/
<?php
/*
Plugin Name: My New Google Analytics Plugin
Plugin URI: http://ylefebvre.ca
Description: New revolutionary GA Plugin
Version: 1.0
Author: Yannick Lefebvre
Author URI: http://ylefebvre.ca
License: GPL2
*/
●
Registers the plugin with WordPress
●
Data visible to users in the Plugins admin section
First plugin sighting
Turning functions.php code into a plugin
<?php
/*
Plugin Name: Add favicon
Plugin URI: http://ylefebvre.ca
Description: Add favicon to site
Version: 1.0
Author: Yannick Lefebvre
Author URI: http://ylefebvre.ca
License: GPL2
*/
function ylefebvre_add_favicon(){ ?>
<link rel="shortcut icon" href="<?php echo
get_stylesheet_directory_uri();?>/images/favicon.ico"/>
<?php }
add_action( 'wp_head', 'ylefebvre_add_favicon' );
<?php
/*
Plugin Name: Add favicon
Plugin URI: http://ylefebvre.ca
Description: Add favicon to site
Version: 1.0
Author: Yannick Lefebvre
Author URI: http://ylefebvre.ca
License: GPL2
*/
function ylefebvre_add_favicon(){ ?>
<link rel="shortcut icon" href="<?php echo
get_stylesheet_directory_uri();?>/images/favicon.ico"/>
<?php }
add_action( 'wp_head', 'ylefebvre_add_favicon' );
Three powerful tools
Shortcodes
Action
hooks
Filter
hooks
Three powerful tools
Action Hook
Do you want to do something
when an event occurs?
Filter Hook Shortcode
Three powerful tools
Action Hook
Do you want to do something
when an event occurs?
Event
WordPress is displaying page
header
Response
Execute plugin code to display
additional header content
Filter Hook Shortcode
Three powerful tools
Action Hook
Do you want to do something
when an event occurs?
Event
WordPress is displaying page
header
Response
Execute plugin code to display
additional header content
Filter Hook
Do you want to modify data
before it is displayed?
Shortcode
Three powerful tools
Action Hook
Do you want to do something
when an event occurs?
Event
WordPress is displaying page
header
Response
Execute plugin code to display
additional header content
Filter Hook
Do you want to modify data
before it is displayed?
Event
WordPress is preparing posts
to be displayed
Response
Execute plugin code to add
Javascript code to all links
Shortcode
Three powerful tools
Action Hook
Do you want to do something
when an event occurs?
Event
WordPress is displaying page
header
Response
Execute plugin code to display
additional header content
Filter Hook
Do you want to modify data
before it is displayed?
Provide easy-to-use code for
users to add content to site
Event
WordPress is preparing posts
to be displayed
Response
Execute plugin code to add
Javascript code to all links
Shortcode
Three powerful tools
Action Hook
Do you want to do something
when an event occurs?
Event
WordPress is displaying page
header
Response
Execute plugin code to display
additional header content
Filter Hook
Do you want to modify data
before it is displayed?
Provide easy-to-use code for
users to add content to site
Event
WordPress is preparing posts
to be displayed
Response
Execute plugin code to add
Javascript code to all links
Shortcode
Event
User has placed shortcode in
page content
Response
Generate content and send
back to WP
Assigning an action hook
add_action( 'hook_name', 'your_function_name',
[priority], [accepted_args] );
Example
add_action( 'wp_head', 'newga_header' );
add_action( 'hook_name', 'your_function_name',
[priority], [accepted_args] );
Example
add_action( 'wp_head', 'newga_header' );
●
Most hook names can be found in WordPress Codex or other
repositories
●
864 action hooks
●
You can learn about hooks by looking into WP source code:
function wp_head() {
do_action( 'wp_head' );
}
function wp_head() {
do_action( 'wp_head' );
}
Full action hook implementation
/* Header code */
add_action( 'wp_head', 'newga_header' );
function newga_header() { ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;
i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();
a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;
m.parentNode.insertBefore(a,m)})(window,document,'script',
'https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-0000000-0', 'auto');
ga('send', 'pageview');
</script>
<? }
/* Header code */
add_action( 'wp_head', 'newga_header' );
function newga_header() { ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;
i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();
a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;
m.parentNode.insertBefore(a,m)})(window,document,'script',
'https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-0000000-0', 'auto');
ga('send', 'pageview');
</script>
<? }
Full action hook implementation
Assigning a filter hook
add_filter( 'filter_name', 'your_function_name',
[priority], [accepted_args] );
Example
add_filter( 'the_content', 'newga_content_filter' );
add_filter( 'filter_name', 'your_function_name',
[priority], [accepted_args] );
Example
add_filter( 'the_content', 'newga_content_filter' );
●
Receive data that can be modified and returned
●
1674 filter hooks
function the_content($more_link_text = null, $stripteaser = 0)
{
$content = get_the_content($more_link_text, $stripteaser);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content;
}
function the_content($more_link_text = null, $stripteaser = 0)
{
$content = get_the_content($more_link_text, $stripteaser);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);
echo $content;
}
Full filter hook implementation
add_filter( 'the_content', 'newga_content_filter' );
function newga_content_filter( $the_content ) {
$new_content = str_replace( 'href',
'onClick="recordOutboundLink( this );return false;" href'
, $the_content );
return $new_content;
}
add_filter( 'the_content', 'newga_content_filter' );
function newga_content_filter( $the_content ) {
$new_content = str_replace( 'href',
'onClick="recordOutboundLink( this );return false;" href'
, $the_content );
return $new_content;
}
●
Add Javascript function call to any links found in content
Full filter hook implementation
Full filter hook implementation
add_action( 'wp_footer', 'footer_analytics_code' );
function footer_analytics_code() { ?>
<script type="text/javascript">
function recordOutboundLink( link ) {
ga( 'send', 'event', 'Outbound Links', 'Click',
link.href, {
'transport': 'beacon',
'hitCallback': function() {
document.location = link.href;
}
} );
}
</script>
<?php }
add_action( 'wp_footer', 'footer_analytics_code' );
function footer_analytics_code() { ?>
<script type="text/javascript">
function recordOutboundLink( link ) {
ga( 'send', 'event', 'Outbound Links', 'Click',
link.href, {
'transport': 'beacon',
'hitCallback': function() {
document.location = link.href;
}
} );
}
</script>
<?php }
Adding a shortcode
●
Simple codes used in a post or page to insert content
– [gallery]
– [gallery id="123" size="medium"]
●
Can be used to output special code before and afer content
– [style1]My text block[/style1]
– Ofen introduced by themes
●
If you repeatedly insert similar code on site, make a
shortcode
Shortcode Implementation
●
Since shortcodes are found anywhere within posts / pages,
they must return their output
add_shortcode( 'dq', 'mysite_div_quote' );
function mysite_div_quote( $atts, $content = null ) {
if ( !empty( $content ) ) {
return '<div class="site_quote" style="text-
align:right">' . $content . '</div>';
}
}
add_shortcode( 'dq', 'mysite_div_quote' );
function mysite_div_quote( $atts, $content = null ) {
if ( !empty( $content ) ) {
return '<div class="site_quote" style="text-
align:right">' . $content . '</div>';
}
}
[dq]This is my text[/dq][dq]This is my text[/dq]
Shortcode Implementation
add_shortcode( 'twitterfeed', 'twitter_embed_shortcode' );
function twitter_embed_shortcode( $args ) {
extract( shortcode_atts( array(
'user_name' => 'ylefebvre'
), $args ) );
if ( !empty( $user_name ) ) {
$output = '<a class="twitter-timeline" href="';
$output .= esc_url( 'https://twitter.com/' .
$user_name );
$output .= '">Tweets by ' . esc_html( $user_name );
$output .= '</a><script async ';
$output .= 'src="//platform.twitter.com/widgets.js"';
$output .= ' charset="utf-8"></script>';
} else {
$output = '';
}
return $output;
}
add_shortcode( 'twitterfeed', 'twitter_embed_shortcode' );
function twitter_embed_shortcode( $args ) {
extract( shortcode_atts( array(
'user_name' => 'ylefebvre'
), $args ) );
if ( !empty( $user_name ) ) {
$output = '<a class="twitter-timeline" href="';
$output .= esc_url( 'https://twitter.com/' .
$user_name );
$output .= '">Tweets by ' . esc_html( $user_name );
$output .= '</a><script async ';
$output .= 'src="//platform.twitter.com/widgets.js"';
$output .= ' charset="utf-8"></script>';
} else {
$output = '';
}
return $output;
}
Shortcode Implementation
●
The resulting shortcode [twitterfeed user_name='WordPress'][twitterfeed user_name='WordPress']
becomes
More tools
Admin menu
More tools
Admin menu Admin pages
More tools
Admin menu Admin pages Extend user editor
More tools
Admin menu Admin pages
Custom post types
Extend user editor
More tools
Admin menu Admin pages
Custom post types
Add custom meta
boxes to any editor
Extend user editor
More tools
Admin menu Admin pages
Custom post types
Add custom meta
boxes to any editor
Extend user editor
New
widgets
More tools
Admin menu Admin pages
Custom post types
Add custom meta
boxes to any editor
Extend user editor
New
widgets
Plugin translation
More tools
●
Store and retrieve plugin settings from site database
●
Query posts
●
Insert styles and scripts in page header and footer
●
Directly access database
Considerations
●
Function names must be diferent from WordPress core
functions and other plugins
●
Entire content is evaluated each time site
is rendered
●
A single error will usually bring down the
entire site
●
Using a local development environment is much safer than
developing on live site
Publishing your plugin
●
wordpress.org oficial repository
– Free plugins only
– Must follow GPL license
– Discoverable from admin plugins page
– Built-in update mechanism
●
Marketplaces (CodeCanyon, MOJO Marketplace, WPEden,
etc…)
– Paid premium plugins
– Need to implement custom update method
– Higher level of support expectation
Conclusions
●
Creating a plugin can be created using very few lines of code
●
When you deliver customer projects, make plugins over
adding code to functions.php
●
Consider distributing your plugins to WordPress community
Recommended Readings
●
WordPress Plugin Development
Cookbook, Second Edition by
Yannick Lefebvre, Packt Publishing
●
WordPress Codex
(codex.wordpress.com)
●
PHP.net
●
StackOverflow.com Programming
Samples
●
Today's presentation and code
samples available at:
– http://ylefebvre.ca/wcmtl2017 WPDCSEd50
Questions?
Thank you for attending this talk on
Plugin Development Demystified
Yannick Lefebvre
@ylefebvre
ylefebvre.ca

More Related Content

PDF
So, you want to be a plugin developer?
PPTX
The Open-source Eclipse Plugin for Force.com Development, Summer ‘14
PDF
A Simple Plugin Architecture for Wicket
PDF
An easy guide to Plugin Development
PPTX
Eclipse Overview
PPTX
Configuration as Code: The Job DSL Plugin
PDF
Jumping Into WordPress Plugin Programming
ODP
The Future Of WordPress Presentation
So, you want to be a plugin developer?
The Open-source Eclipse Plugin for Force.com Development, Summer ‘14
A Simple Plugin Architecture for Wicket
An easy guide to Plugin Development
Eclipse Overview
Configuration as Code: The Job DSL Plugin
Jumping Into WordPress Plugin Programming
The Future Of WordPress Presentation

What's hot (20)

PPTX
How to develope plugin in wordpress: 6 simple steps.
PDF
Step by step guide for creating wordpress plugin
PDF
Wordpress Plugin Development Short Tutorial
PDF
How to WordPress: the basics, part 1
PPTX
Responsive Theme Workshop - WordCamp Columbus 2015
ODP
WordPress Plugin Development For Beginners
ODP
Beginning WordPress Plugin Development
PDF
WordPress plugin development
PPTX
Plugin architecture (Extensible Application Architecture)
PPTX
Creating a Plug-In Architecture
PDF
Ako na vlastne WP temy
PDF
Building mobile applications with DrupalGap
PPT
Word press Plugins by WordPress Experts
PPT
Developing Plugins For WordPress
PPT
PDF
Behaviour Driven Development con Behat & Drupal
PPTX
Extension developer secrets - How to make money with Joomla
PDF
Plugins at WordCamp Phoenix
PDF
Theming in WordPress - Where do I Start?
PDF
Wordpress Questions & Answers
How to develope plugin in wordpress: 6 simple steps.
Step by step guide for creating wordpress plugin
Wordpress Plugin Development Short Tutorial
How to WordPress: the basics, part 1
Responsive Theme Workshop - WordCamp Columbus 2015
WordPress Plugin Development For Beginners
Beginning WordPress Plugin Development
WordPress plugin development
Plugin architecture (Extensible Application Architecture)
Creating a Plug-In Architecture
Ako na vlastne WP temy
Building mobile applications with DrupalGap
Word press Plugins by WordPress Experts
Developing Plugins For WordPress
Behaviour Driven Development con Behat & Drupal
Extension developer secrets - How to make money with Joomla
Plugins at WordCamp Phoenix
Theming in WordPress - Where do I Start?
Wordpress Questions & Answers
Ad

Similar to Plugin development demystified 2017 (20)

PDF
Write your first WordPress plugin
PDF
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
PPTX
Getting started with WordPress development
PDF
Developing WordPress Plugins : For Begineers
PPT
WordPress Plugin Development- Rich Media Institute Workshop
PDF
WordCamp Asheville 2017 - So You Wanna Dev? Join the Team!
PDF
Intro to WordPress Plugin Development
PDF
WordPress Plugin Development 201
PPSX
Extending WordPress
PDF
Write Your First WordPress Plugin
PDF
Creating Extensible Plugins for WordPress
PPTX
WordPress Internationalization and Localization - WordPress Translation Day 3...
PDF
Best Wordprees development company in bangalore
PDF
Website development PDF which helps others make it easy
PDF
5 Steps to Develop a WordPress Plugin From Scratch.pdf
PDF
Using the new WordPress REST API
PDF
Wordpress as a framework
PDF
Creating Your First WordPress Plugin
PPTX
Faster WordPress Workflows
PPS
Simplify your professional web development with symfony
Write your first WordPress plugin
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
Getting started with WordPress development
Developing WordPress Plugins : For Begineers
WordPress Plugin Development- Rich Media Institute Workshop
WordCamp Asheville 2017 - So You Wanna Dev? Join the Team!
Intro to WordPress Plugin Development
WordPress Plugin Development 201
Extending WordPress
Write Your First WordPress Plugin
Creating Extensible Plugins for WordPress
WordPress Internationalization and Localization - WordPress Translation Day 3...
Best Wordprees development company in bangalore
Website development PDF which helps others make it easy
5 Steps to Develop a WordPress Plugin From Scratch.pdf
Using the new WordPress REST API
Wordpress as a framework
Creating Your First WordPress Plugin
Faster WordPress Workflows
Simplify your professional web development with symfony
Ad

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Big Data Technologies - Introduction.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Approach and Philosophy of On baking technology
PDF
cuic standard and advanced reporting.pdf
PDF
Advanced IT Governance
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Advanced methodologies resolving dimensionality complications for autism neur...
Dropbox Q2 2025 Financial Results & Investor Presentation
Big Data Technologies - Introduction.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Approach and Philosophy of On baking technology
cuic standard and advanced reporting.pdf
Advanced IT Governance
MYSQL Presentation for SQL database connectivity
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Reach Out and Touch Someone: Haptics and Empathic Computing
Advanced Soft Computing BINUS July 2025.pdf
Unlocking AI with Model Context Protocol (MCP)
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Review of recent advances in non-invasive hemoglobin estimation
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?

Plugin development demystified 2017

  • 1. Yannick Lefebvre @ylefebvre ylefebvre.ca WordPress Plugin Developer / Author Plugin Development Demystified Second Edition
  • 2. Topics ● Plugins Overview ● Types of plugin developers ● Plugins vs functions.php ● File Structure ● Required Tools ● Plugin file header ● Turning functions.php code into a plugin ● Actions hook ● Filter hook ● Shortcodes ● More tools ● Considerations ● Publishing your plugin ● Recommended Readings ● Questions Plugin Development Demystified Slides at ylefebvre.ca/wcmtl2017
  • 3. About me ● WordPress user since 2004 ● Released first plugin in 2005 ● 8 plugins on oficial repository ● Author of WordPress Plugin Development Cookbook, Second Edition – Use code WPDCSEd50 to get 50% of eBook on packtpub.com until Sept 12 ● Custom plugin development Slides at ylefebvre.ca/wcmtl2017
  • 4. Plugins Overview ● Extend WordPress capabilities ● Open plugin architecture ● Ofer function of varying complexity ● More than 50,000 plugins available today!
  • 5. Plugins Overview ● Extend WordPress capabilities ● Open plugin architecture ● Ofer function of varying complexity ● More than 50,000 plugins available today! Who makes these plugins and what tools do they use to make them?
  • 6. Types of plugin developers Site administrator Website developer Community developerFreelance developer
  • 7. Plugins vs functions.php ● Ever written your own plugin?
  • 8. Plugins vs functions.php ● Ever written your own plugin? ● Ever added code to functions.php on your own site or in a customer project? function ylefebvre_add_favicon(){ ?> <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/images/favicon.ico"/> <?php } add_action( 'wp_head', 'ylefebvre_add_favicon' ); function ylefebvre_add_favicon(){ ?> <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/images/favicon.ico"/> <?php } add_action( 'wp_head', 'ylefebvre_add_favicon' );
  • 9. Plugins vs functions.php ● Ever written your own plugin? functions.php code is 99%of the way towards making a plugin with 0%of the benefits ● Ever added code to functions.php on your own site or in a customer project? function ylefebvre_add_favicon(){ ?> <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/images/favicon.ico"/> <?php } add_action( 'wp_head', 'ylefebvre_add_favicon' ); function ylefebvre_add_favicon(){ ?> <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/images/favicon.ico"/> <?php } add_action( 'wp_head', 'ylefebvre_add_favicon' );
  • 10. Plugins vs functions.php Benefit functions.php Plugin Easily activated or deactivated without need to search or risk of afecting other code Theme-independent Easy to update in customer installations
  • 11. Basic Plugin File Structure ● One or more plain text php code file(s) ● Can contain other file types (e.g. images, text files, translation files, etc…) ● Distributed as zip file
  • 13. Required Tools Optional ● Code editor (e.g. Notepad++, Programmer’s Notepad, Sublime Text)
  • 15. Required Tools Optional ● Image Editor ● Local web server – VVV – Varying Vagrant Vagrants – XAMPP – MAMP – WSL – Windows Subsystem for Linux) ● Archive Tool
  • 16. Plugin File Header <?php /* Plugin Name: My New Google Analytics Plugin Plugin URI: http://ylefebvre.ca Description: New revolutionary GA Plugin Version: 1.0 Author: Yannick Lefebvre Author URI: http://ylefebvre.ca License: GPL2 */ <?php /* Plugin Name: My New Google Analytics Plugin Plugin URI: http://ylefebvre.ca Description: New revolutionary GA Plugin Version: 1.0 Author: Yannick Lefebvre Author URI: http://ylefebvre.ca License: GPL2 */ ● Registers the plugin with WordPress ● Data visible to users in the Plugins admin section
  • 18. Turning functions.php code into a plugin <?php /* Plugin Name: Add favicon Plugin URI: http://ylefebvre.ca Description: Add favicon to site Version: 1.0 Author: Yannick Lefebvre Author URI: http://ylefebvre.ca License: GPL2 */ function ylefebvre_add_favicon(){ ?> <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri();?>/images/favicon.ico"/> <?php } add_action( 'wp_head', 'ylefebvre_add_favicon' ); <?php /* Plugin Name: Add favicon Plugin URI: http://ylefebvre.ca Description: Add favicon to site Version: 1.0 Author: Yannick Lefebvre Author URI: http://ylefebvre.ca License: GPL2 */ function ylefebvre_add_favicon(){ ?> <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri();?>/images/favicon.ico"/> <?php } add_action( 'wp_head', 'ylefebvre_add_favicon' );
  • 20. Three powerful tools Action Hook Do you want to do something when an event occurs? Filter Hook Shortcode
  • 21. Three powerful tools Action Hook Do you want to do something when an event occurs? Event WordPress is displaying page header Response Execute plugin code to display additional header content Filter Hook Shortcode
  • 22. Three powerful tools Action Hook Do you want to do something when an event occurs? Event WordPress is displaying page header Response Execute plugin code to display additional header content Filter Hook Do you want to modify data before it is displayed? Shortcode
  • 23. Three powerful tools Action Hook Do you want to do something when an event occurs? Event WordPress is displaying page header Response Execute plugin code to display additional header content Filter Hook Do you want to modify data before it is displayed? Event WordPress is preparing posts to be displayed Response Execute plugin code to add Javascript code to all links Shortcode
  • 24. Three powerful tools Action Hook Do you want to do something when an event occurs? Event WordPress is displaying page header Response Execute plugin code to display additional header content Filter Hook Do you want to modify data before it is displayed? Provide easy-to-use code for users to add content to site Event WordPress is preparing posts to be displayed Response Execute plugin code to add Javascript code to all links Shortcode
  • 25. Three powerful tools Action Hook Do you want to do something when an event occurs? Event WordPress is displaying page header Response Execute plugin code to display additional header content Filter Hook Do you want to modify data before it is displayed? Provide easy-to-use code for users to add content to site Event WordPress is preparing posts to be displayed Response Execute plugin code to add Javascript code to all links Shortcode Event User has placed shortcode in page content Response Generate content and send back to WP
  • 26. Assigning an action hook add_action( 'hook_name', 'your_function_name', [priority], [accepted_args] ); Example add_action( 'wp_head', 'newga_header' ); add_action( 'hook_name', 'your_function_name', [priority], [accepted_args] ); Example add_action( 'wp_head', 'newga_header' ); ● Most hook names can be found in WordPress Codex or other repositories ● 864 action hooks ● You can learn about hooks by looking into WP source code: function wp_head() { do_action( 'wp_head' ); } function wp_head() { do_action( 'wp_head' ); }
  • 27. Full action hook implementation /* Header code */ add_action( 'wp_head', 'newga_header' ); function newga_header() { ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r; i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date(); a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g; m.parentNode.insertBefore(a,m)})(window,document,'script', 'https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-0000000-0', 'auto'); ga('send', 'pageview'); </script> <? } /* Header code */ add_action( 'wp_head', 'newga_header' ); function newga_header() { ?> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r; i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date(); a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g; m.parentNode.insertBefore(a,m)})(window,document,'script', 'https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-0000000-0', 'auto'); ga('send', 'pageview'); </script> <? }
  • 28. Full action hook implementation
  • 29. Assigning a filter hook add_filter( 'filter_name', 'your_function_name', [priority], [accepted_args] ); Example add_filter( 'the_content', 'newga_content_filter' ); add_filter( 'filter_name', 'your_function_name', [priority], [accepted_args] ); Example add_filter( 'the_content', 'newga_content_filter' ); ● Receive data that can be modified and returned ● 1674 filter hooks function the_content($more_link_text = null, $stripteaser = 0) { $content = get_the_content($more_link_text, $stripteaser); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]&gt;', $content); echo $content; } function the_content($more_link_text = null, $stripteaser = 0) { $content = get_the_content($more_link_text, $stripteaser); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]&gt;', $content); echo $content; }
  • 30. Full filter hook implementation add_filter( 'the_content', 'newga_content_filter' ); function newga_content_filter( $the_content ) { $new_content = str_replace( 'href', 'onClick="recordOutboundLink( this );return false;" href' , $the_content ); return $new_content; } add_filter( 'the_content', 'newga_content_filter' ); function newga_content_filter( $the_content ) { $new_content = str_replace( 'href', 'onClick="recordOutboundLink( this );return false;" href' , $the_content ); return $new_content; } ● Add Javascript function call to any links found in content
  • 31. Full filter hook implementation
  • 32. Full filter hook implementation add_action( 'wp_footer', 'footer_analytics_code' ); function footer_analytics_code() { ?> <script type="text/javascript"> function recordOutboundLink( link ) { ga( 'send', 'event', 'Outbound Links', 'Click', link.href, { 'transport': 'beacon', 'hitCallback': function() { document.location = link.href; } } ); } </script> <?php } add_action( 'wp_footer', 'footer_analytics_code' ); function footer_analytics_code() { ?> <script type="text/javascript"> function recordOutboundLink( link ) { ga( 'send', 'event', 'Outbound Links', 'Click', link.href, { 'transport': 'beacon', 'hitCallback': function() { document.location = link.href; } } ); } </script> <?php }
  • 33. Adding a shortcode ● Simple codes used in a post or page to insert content – [gallery] – [gallery id="123" size="medium"] ● Can be used to output special code before and afer content – [style1]My text block[/style1] – Ofen introduced by themes ● If you repeatedly insert similar code on site, make a shortcode
  • 34. Shortcode Implementation ● Since shortcodes are found anywhere within posts / pages, they must return their output add_shortcode( 'dq', 'mysite_div_quote' ); function mysite_div_quote( $atts, $content = null ) { if ( !empty( $content ) ) { return '<div class="site_quote" style="text- align:right">' . $content . '</div>'; } } add_shortcode( 'dq', 'mysite_div_quote' ); function mysite_div_quote( $atts, $content = null ) { if ( !empty( $content ) ) { return '<div class="site_quote" style="text- align:right">' . $content . '</div>'; } } [dq]This is my text[/dq][dq]This is my text[/dq]
  • 35. Shortcode Implementation add_shortcode( 'twitterfeed', 'twitter_embed_shortcode' ); function twitter_embed_shortcode( $args ) { extract( shortcode_atts( array( 'user_name' => 'ylefebvre' ), $args ) ); if ( !empty( $user_name ) ) { $output = '<a class="twitter-timeline" href="'; $output .= esc_url( 'https://twitter.com/' . $user_name ); $output .= '">Tweets by ' . esc_html( $user_name ); $output .= '</a><script async '; $output .= 'src="//platform.twitter.com/widgets.js"'; $output .= ' charset="utf-8"></script>'; } else { $output = ''; } return $output; } add_shortcode( 'twitterfeed', 'twitter_embed_shortcode' ); function twitter_embed_shortcode( $args ) { extract( shortcode_atts( array( 'user_name' => 'ylefebvre' ), $args ) ); if ( !empty( $user_name ) ) { $output = '<a class="twitter-timeline" href="'; $output .= esc_url( 'https://twitter.com/' . $user_name ); $output .= '">Tweets by ' . esc_html( $user_name ); $output .= '</a><script async '; $output .= 'src="//platform.twitter.com/widgets.js"'; $output .= ' charset="utf-8"></script>'; } else { $output = ''; } return $output; }
  • 36. Shortcode Implementation ● The resulting shortcode [twitterfeed user_name='WordPress'][twitterfeed user_name='WordPress'] becomes
  • 38. More tools Admin menu Admin pages
  • 39. More tools Admin menu Admin pages Extend user editor
  • 40. More tools Admin menu Admin pages Custom post types Extend user editor
  • 41. More tools Admin menu Admin pages Custom post types Add custom meta boxes to any editor Extend user editor
  • 42. More tools Admin menu Admin pages Custom post types Add custom meta boxes to any editor Extend user editor New widgets
  • 43. More tools Admin menu Admin pages Custom post types Add custom meta boxes to any editor Extend user editor New widgets Plugin translation
  • 44. More tools ● Store and retrieve plugin settings from site database ● Query posts ● Insert styles and scripts in page header and footer ● Directly access database
  • 45. Considerations ● Function names must be diferent from WordPress core functions and other plugins ● Entire content is evaluated each time site is rendered ● A single error will usually bring down the entire site ● Using a local development environment is much safer than developing on live site
  • 46. Publishing your plugin ● wordpress.org oficial repository – Free plugins only – Must follow GPL license – Discoverable from admin plugins page – Built-in update mechanism ● Marketplaces (CodeCanyon, MOJO Marketplace, WPEden, etc…) – Paid premium plugins – Need to implement custom update method – Higher level of support expectation
  • 47. Conclusions ● Creating a plugin can be created using very few lines of code ● When you deliver customer projects, make plugins over adding code to functions.php ● Consider distributing your plugins to WordPress community
  • 48. Recommended Readings ● WordPress Plugin Development Cookbook, Second Edition by Yannick Lefebvre, Packt Publishing ● WordPress Codex (codex.wordpress.com) ● PHP.net ● StackOverflow.com Programming Samples ● Today's presentation and code samples available at: – http://ylefebvre.ca/wcmtl2017 WPDCSEd50
  • 49. Questions? Thank you for attending this talk on Plugin Development Demystified Yannick Lefebvre @ylefebvre ylefebvre.ca