SlideShare a Scribd company logo
WordPress Plugin #3
May 21st, 2015
changwoo
Recap
Hooks in Nutshell
● Hook is an event
● Plugin is hook-driven
● Task separation
o Changing core's workflow: action
o Modifying contents: filter
o In fact, action and filter are the same
Recap
Hooks in Nutshell
● Callback function utility
● You can define your own hooks
● There are many predefined hooks
Recap
Datbase Nutshell
● Parent-meta strategy
o Flexiblility
o Extendible
o But can experience some defects
● Meta key, meta value
o Hash-like storage
Recap
Database Nutshell
● Term, taxonomy
o Term: a word
o Taxonomy: a classification of words
● There are some pre-defined terms, and
taxonomies
o category (hierarchical), post_tag (flat)
Recap
Today's Topics
1.Entry Points in Plugin
a. Menu
b. Shortcodes
c. Admin Post
d. Ajax
e. Redirect
f. activation, deactivation, uninstall
2.Managing Your Own Contents
a. All About Custom Posts
Entry Points in Plugin
Entry Points
Plugins run on the server side.
Server only responds when it is requested.
Requested moment → entry point
Entry Points
Q. When the server is requested?
A. It is when client access via a URL.
Q. Why a URL is used?
A. To define a resource: output to client
A. To receive data: input from client
Entry Points
Q. Output Form?
A. Whatever,
Images, audio, video, html documents, ...
Q. Input form?
A. Generally submitting forms
via GET/POST method.
Entry Points
There are some special entry points left for
plugins
● Menu items
● Shortcodes
● Admin post
● AJAX
● Redirecting
● Activation, deactivation, uninstall
Menu Items
Callback from admin menu clicking
add_menu_page()
add_submenu_page()
remove_menu_page()
remove_submenu_page()
Where is default menu?
wp-admin/menu-header.php
<ul id="adminmenu">
<?php
_wp_menu_output( $menu, $submenu );
function _wp_menu_output( $menu, $submenu, $submenu_as_parent = true )
here menus are printed in html
Where is default menu?
wp-admin/menu.php (admin.php includes it)
wp-amdin/includes/menu.php
builds administrative menus
global $menu, $submenu stores menu
information
Our custom menus
wp-admin/includes/menu.php
do_action( 'admin_menu', '' );
Menu API are defined in wp-
admin/includes/plugin.php
add_menu_page
function add_menu_page( $page_title, $menu_title, $capability, $menu_slug,
$function = '', $icon_url = '', $position = null ) {
...
$new_menu = array( $menu_title, $capability, $menu_slug, $page_title,
'menu-top ' . $icon_class . $hookname, $hookname, $icon_url );
if ( null === $position )
$menu[] = $new_menu;
else
$menu[$position] = $new_menu;
add_submenu_page
function add_submenu_page( $parent_slug, $page_title, $menu_title,
$capability, $menu_slug, $function = '' ) {
...
$submenu[$parent_slug][] = array ( $menu_title, $capability, $menu_slug,
$page_title );
...
}
derivatives
● add_dashboard_page()
● add_posts_page()
● add_media_page()
● add_pages_page()
● add_comments_page()
● add_theme_page()
● add_plugins_page()
● add_users_page()
● add_management_page()
● add_options_page()
Shortcodes
What is shortcode?
A "magic word" in post content that is
replaced by some process defined in plugin
or themes in runtime.
Good for displaying complex, dynamic
contents
Shortcodes
Sample:
[gallery id="123" size="medium"]
[gallery]
or
[caption]My Caption[/caption] *enclosed form
Shortcodes
add_shortcode()
$shortcode_tags = array();
function add_shortcode($tag, $func) {
global $shortcode_tags;
if ( is_callable($func) )
$shortcode_tags[$tag] = $func;
}
Shortcodes
function do_shortcode($content) {
global $shortcode_tags;
if ( false === strpos( $content, '[' ) ) {
return $content;
}
if (empty($shortcode_tags) || !is_array($shortcode_tags))
return $content;
$pattern = get_shortcode_regex();
return preg_replace_callback( "/$pattern/s", 'do_shortcode_tag',
$content );
}
Shortcodes
function do_shortcode_tag( $m ) {
...
if ( isset( $m[5] ) ) {
// enclosing tag - extra parameter
return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, $m[5],
$tag ) . $m[6];
} else {
// self-closing tag
return $m[1] . call_user_func( $shortcode_tags[$tag], $attr, null,
$tag ) . $m[6];
}
}
Shortcodes
callback params
● $attrs: attributes
● $content: enclosed tag's text
● $tag: shortcode tag itself
Admin-post
Data from clients.
Processing requests.
You can just process requests in your own
page because $_REQUEST, $_GET, $_POST is
global.
Admin-post
But in your own handler,
You cannot use WP core functions.
You cannot authenticate.
Do not reinvent the wheel!
So there is admin-post.php
Admin-post
wp-admin/admin-post.php
define & include minimal settings,
and do_action
$action = empty( $_REQUEST['action'] ) ? '' : $_REQUEST['action'];
admin_post_nopriv, admin_post_nopriv_{$action}
admin_post, admin_post_{$action}
finish using die() in callback function!
AJAX
Very similar to admin-post, but 'DOING_AJAX' is defined:
define( 'DOING_AJAX', true );
also use die() in callback function
if ( is_user_logged_in() ) {
do_action( 'wp_ajax_' . $_REQUEST['action'] );
} else {
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
// Default status
die( '0' );
Redirect
You can generate custom page in plugin, by
using 'template_redirect' action.
function my_page_template_redirect() {
if( is_page( 'goodies' ) && ! is_user_logged_in() ) {
wp_redirect( home_url( '/signup/' ) );
exit();
}
}
add_action( 'template_redirect', 'my_page_template_redirect' );
Redirect
You can generate web pages on-the-fly by
utilizing these 3 hooks.
● rewrite rule
● query parsing
● redirect
Detailed instructions, later
(de)activation, uninstall
register_activation_hook($file, $cb)
register_deactivation_hook($file, $cb)
register_uninstall_hook($file, $cb)
$file: full path of plugin file
$cb: callback function
● callbacks should be "SILENT". No echo please.
Summary
● menu items, shortcodes, admin post, ajax,
template redirects, and (de)activation-
uninstall hooks are good initial entry
points.
o It is a good strategy to find these
hooks in plugins first and dissect
their codes from those points.
I know you want to do something!
You understand hook concept.
You know database detail.
Now you know entry points
Definitely, you wanna make something.
Visit http://[ip]/practice/ and download entry-points.php
소스코드: http://[ip]/source-codes/
1.어드민 화면에 메뉴 추가
2.쇼트코드 추가
3.메뉴에서 admin post 전송
4.메뉴에서 ajax 전송
5.redirect 테스트
<author> 부분은 자신의 이름으로 일괄변경하고,
적절히 콜백 함수를 정의해 주세요.
Source code explained
10 minutes break
Managing Your Own Contents
Wow, there are too many
things about posts!
For today, just focuse on
"custom post type"
Arguments are too complex!
Just use Types, or Pods plugin.
Thats' all, problem solved!
Yeah!
... of course, you might not want
this. I was just kidding.
Custom Post
You want to manage your own contents.
That's why custom post is.
● Music collections
● Online store
● Event calendar
● Book data
● Photo portfolio
Custom Post: Motivation
Well, with just one type "post", and you may
define many categories and use them to
organize all contents.
JUST ONE TYPE: POST
MANY CATEGORIES:
portfolio, calendar, music db, ...
Custom Post: Motivation
But you might feel that some post types:
● should be hidden from some users
● even might be excluded from search
● may be only for private use
● may have very complex taxonomies.
so that it should have its own
territory.
● can be accessible from their own URL
rules
Custom Post: Motivation
Why re-invent wheel again?
By extending built-in post type system,
you can REUSE whole facilities related to
posts easily!
UI, and all thing about managing
Built-in Custom Post Types
wp-includes/post.php (included in wp-settings.php)
function create_initial_post_types() {
register_post_type( 'post', array( ...
register_post_type( 'page', array( ...
register_post_type( 'attachment', array( ...
register_post_type( 'revision', array( ...
register_post_type( 'nav_menu_item', array( ...
register_post_status( 'publish', array( ...
...
register_post_type
<?php register_post_type( $post_type, $args ); ?>
$arg is very complex.
But I think it should be explained in detail. Actually,
you cannot avoid it, because eventuall all post type
plugins will use that function, too.
Those plugins also have diffcult UIs, too.
register_post_type
Let's take a look how Types, and Pods create
their custom posts...
They have easy (really?) UI and provide
better functionaliy, but you can see
horribly many options there.
register_post_type $post_type
● Up to 20 characters
● Only lowercase and numbers
register_post_type $args
public:
visible to authors
true implies
exclude_from_search: false,
publicly_queryable, show_in_nav_manues, show_ui
false implies
exclude_from_search: true, publicly_queryable: false,
show_in_nav_manues: false, show_ui: false
register_post_type $args
label:
plural descriptive name
e.g:
"Music Collections"
Mostly localized text
register_post_type $args
labels: more specific text labels
name
sigular_name
menu_name
name_admin_bar
all_items
add_new
add_new_item
edit_item
view_item
search_items
search_items
not_found
not_found in trash
parent_item_colon
register_post_type $args
description:
summary of this post type
register_post_type $args
exclude_from_search:
do not search this post type
try '/S=beatbles'
register_post_type $args
publicly_queryable:
can use query
e.g) /?post_type=music_collection
register_post_type $args
show_ui:
display default UI
register_post_type $args
show_in_nav_menus:
show in navigation menus
be careful! 'publicly_queryable'
must be true
register_post_type $args
show_in_menu:
show admin_menu. show_ui must be true.
Just showing menu.
true, false, else some strings
(tools.php / edit.php)
altough it is false,
you can access URLS like:
/wp-admin/edit.php?post_type=music_collection
(show_ui must be true!)
register_post_type $args
show_in_admin_bar:
available in admin bar
menu_postion:
default: below comments
menu_icon
see dashicons
register_post_type $args
capability_type:
string or array to build capabilites
in our exampe,
edit_music_collections
edit_others_music_collections
publish_music_collections
read_private_music_collections
register_post_type $args
capabilities:
to give specific names to each capability
map_meta_cap:
if true, default meta capability will be added
and then, your role or account need capabilities
register_post_type $args
hierarchical:
post type can be hierarchical.
this is for page-styles.
register_post_type $args
query_var:
to query posts /?{query_var}={slug}
rewrite:
to use pretty permalinks.
has_archive:
Enables post type archive
register_post_type $args
permalink_epmask:
rewrite endpoint bitmask
can_export:
true makes the post can be exported
Too exhaustive... but worth it.
Practice Custom Post
Create custom-plugin-<author>.php
Create a simple custom post.
Display admin menu,
Hide admin_bar,
Write your post:
● Any content is OK.
● Include at least one meta field.
Next Week.
Customizing Visual Components
● List Table Screen
● Widgets
● ...
WordPress System Undercover
● Constants and Globals
● WPDB

More Related Content

What's hot (20)

PDF
Building Large jQuery Applications
Rebecca Murphey
 
PDF
Virtual Madness @ Etsy
Nishan Subedi
 
PDF
Dojo Confessions
Rebecca Murphey
 
PDF
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Acquia
 
PDF
Как получить чёрный пояс по WordPress? v2.0
Yevhen Kotelnytskyi
 
PDF
Как получить чёрный пояс по WordPress?
Yevhen Kotelnytskyi
 
PPTX
Magento Dependency Injection
Anton Kril
 
PDF
Silex meets SOAP & REST
Hugo Hamon
 
PDF
Drupal is Stupid (But I Love It Anyway)
brockboland
 
PPTX
Routing in Drupal 8
kgoel1
 
ODP
Drupal 8 Routing
Yuriy Gerasimov
 
PDF
Functionality Focused Code Organization
Rebecca Murphey
 
PPTX
Анатолий Поляков - Drupal.ajax framework from a to z
LEDC 2016
 
PDF
Using Objects to Organize your jQuery Code
Rebecca Murphey
 
PPTX
Goodbye hook_menu() - Routing and Menus in Drupal 8
Exove
 
PPTX
Sins Against Drupal 2
Aaron Crosman
 
PDF
Using and reusing CakePHP plugins
Pierre MARTIN
 
PPTX
Beyond DOMReady: Ultra High-Performance Javascript
aglemann
 
PDF
WordPress Capabilities Magic
mannieschumpert
 
PDF
Intro to advanced caching in WordPress
Maor Chasen
 
Building Large jQuery Applications
Rebecca Murphey
 
Virtual Madness @ Etsy
Nishan Subedi
 
Dojo Confessions
Rebecca Murphey
 
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Acquia
 
Как получить чёрный пояс по WordPress? v2.0
Yevhen Kotelnytskyi
 
Как получить чёрный пояс по WordPress?
Yevhen Kotelnytskyi
 
Magento Dependency Injection
Anton Kril
 
Silex meets SOAP & REST
Hugo Hamon
 
Drupal is Stupid (But I Love It Anyway)
brockboland
 
Routing in Drupal 8
kgoel1
 
Drupal 8 Routing
Yuriy Gerasimov
 
Functionality Focused Code Organization
Rebecca Murphey
 
Анатолий Поляков - Drupal.ajax framework from a to z
LEDC 2016
 
Using Objects to Organize your jQuery Code
Rebecca Murphey
 
Goodbye hook_menu() - Routing and Menus in Drupal 8
Exove
 
Sins Against Drupal 2
Aaron Crosman
 
Using and reusing CakePHP plugins
Pierre MARTIN
 
Beyond DOMReady: Ultra High-Performance Javascript
aglemann
 
WordPress Capabilities Magic
mannieschumpert
 
Intro to advanced caching in WordPress
Maor Chasen
 

Viewers also liked (19)

PPT
Dualboot
krtk
 
PPTX
Огонь вечной памяти города Владимира
detmobib
 
PPTX
Install dan setting ip oshirix
krtk
 
PDF
Cukoo srch
siet_pradeep18
 
PPTX
Competencias comunicativas
mariacpar
 
PPTX
Tips for Moving
Home+Lot Connect
 
PPTX
Negosiasi kelas X
annekesyahputri
 
PPT
Blues background lesson 2
crobertstshlc
 
DOCX
Suffix & Prefix
Rahaden Lingga Bhumi
 
PPTX
Accessibility at Regents University
Susan Hastie
 
ODP
Aula 47 52 - 1º cga
Janaína Kaecke
 
PPTX
Data mining
Wasim Raza
 
PDF
حيدر حيدر - إغواء - قصص
Ali Alaaraj
 
PPTX
Técnicas y actividades de aprendizaje
Panamá
 
DOC
Nama murid science fair
Annreetha Anthony
 
PPT
사설토토 ~(?)GUU69,cOm 까톡: up85 ~(?) 토토프로토 해외토토
hgjkl
 
DOC
Zaragoza turismo 305 bis
Saucepolis blog & Hotel Sauce
 
PDF
certificate Inbound
naveedhussain
 
DOCX
Infografía. Pasos para la creación de una empresa en México
Xochitl Rodriguez Marquez
 
Dualboot
krtk
 
Огонь вечной памяти города Владимира
detmobib
 
Install dan setting ip oshirix
krtk
 
Cukoo srch
siet_pradeep18
 
Competencias comunicativas
mariacpar
 
Tips for Moving
Home+Lot Connect
 
Negosiasi kelas X
annekesyahputri
 
Blues background lesson 2
crobertstshlc
 
Suffix & Prefix
Rahaden Lingga Bhumi
 
Accessibility at Regents University
Susan Hastie
 
Aula 47 52 - 1º cga
Janaína Kaecke
 
Data mining
Wasim Raza
 
حيدر حيدر - إغواء - قصص
Ali Alaaraj
 
Técnicas y actividades de aprendizaje
Panamá
 
Nama murid science fair
Annreetha Anthony
 
사설토토 ~(?)GUU69,cOm 까톡: up85 ~(?) 토토프로토 해외토토
hgjkl
 
Zaragoza turismo 305 bis
Saucepolis blog & Hotel Sauce
 
certificate Inbound
naveedhussain
 
Infografía. Pasos para la creación de una empresa en México
Xochitl Rodriguez Marquez
 
Ad

Similar to WordPress plugin #3 (20)

PDF
Django Vs Rails
Sérgio Santos
 
PPTX
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 
PDF
D7 theming what's new - London
Marek Sotak
 
PPTX
WordPress Structure and Best Practices
markparolisi
 
PDF
Best Practices in Plugin Development (WordCamp Seattle)
andrewnacin
 
PDF
Django Heresies
Simon Willison
 
KEY
MTDDC 2010.2.5 Tokyo - Brand new API
Six Apart KK
 
PPTX
WordPress 15th Meetup - Build a Theme
Fadi Nicolas Zahhar
 
PDF
Laying the proper foundation for plugin and theme development
Tammy Hart
 
KEY
Writing extensible Word press-plugins
AllenSnook
 
PDF
TurboGears2 Pluggable Applications
Alessandro Molina
 
PPTX
WordPress for developers - phpday 2011
Maurizio Pelizzone
 
PPTX
8 things to know about theming in drupal 8
Logan Farr
 
KEY
Apostrophe (improved Paris edition)
tompunk
 
PDF
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 
PDF
Gail villanueva add muscle to your wordpress site
references
 
PPTX
Building Potent WordPress Websites
Kyle Cearley
 
PDF
Building a Portfolio With Custom Post Types
Alex Blackie
 
PDF
The Settings API
Konstantin Kovshenin
 
PPTX
WordPress plugin #2
giwoolee
 
Django Vs Rails
Sérgio Santos
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 
D7 theming what's new - London
Marek Sotak
 
WordPress Structure and Best Practices
markparolisi
 
Best Practices in Plugin Development (WordCamp Seattle)
andrewnacin
 
Django Heresies
Simon Willison
 
MTDDC 2010.2.5 Tokyo - Brand new API
Six Apart KK
 
WordPress 15th Meetup - Build a Theme
Fadi Nicolas Zahhar
 
Laying the proper foundation for plugin and theme development
Tammy Hart
 
Writing extensible Word press-plugins
AllenSnook
 
TurboGears2 Pluggable Applications
Alessandro Molina
 
WordPress for developers - phpday 2011
Maurizio Pelizzone
 
8 things to know about theming in drupal 8
Logan Farr
 
Apostrophe (improved Paris edition)
tompunk
 
Aplicacoes dinamicas Rails com Backbone
Rafael Felix da Silva
 
Gail villanueva add muscle to your wordpress site
references
 
Building Potent WordPress Websites
Kyle Cearley
 
Building a Portfolio With Custom Post Types
Alex Blackie
 
The Settings API
Konstantin Kovshenin
 
WordPress plugin #2
giwoolee
 
Ad

Recently uploaded (20)

PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
PPTX
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
PPT
introductio to computers by arthur janry
RamananMuthukrishnan
 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
 
PDF
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
PPTX
一比一原版(LaTech毕业证)路易斯安那理工大学毕业证如何办理
Taqyea
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PPT
Computer Securityyyyyyyy - Chapter 1.ppt
SolomonSB
 
PDF
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
PPT
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
PPTX
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PPTX
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
PPTX
Orchestrating things in Angular application
Peter Abraham
 
PPTX
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
PPTX
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
PPTX
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
introductio to computers by arthur janry
RamananMuthukrishnan
 
introduction to networking with basics coverage
RamananMuthukrishnan
 
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
一比一原版(LaTech毕业证)路易斯安那理工大学毕业证如何办理
Taqyea
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
Computer Securityyyyyyyy - Chapter 1.ppt
SolomonSB
 
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
Orchestrating things in Angular application
Peter Abraham
 
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 

WordPress plugin #3