SlideShare a Scribd company logo
1 of 66
WordCamp Denver 2012
October 13, 2012
Jeremy Green
WordPress Developer at Endo Creative
Organizer of the Fort Collins WordPress Meetup

@greenhornet79
Developing with
Custom Meta Boxes
What is a custom meta box?
It allows you to add a custom piece of
data to a post or page in the
administrative interface.
What about custom fields?
Could use custom fields, but they’re
ugly and not user friendly.
What does
this mean?
Add descriptions
   for users
Dropdown
   Radio Buttons
Select



          Text Box
How to add a custom meta
box to your plugin or theme
add_meta_box( $args );
$id
(required)


HTML ‘id’ attribute of the edit screen section
$title
(required)


Title of the edit screen section, visible to the user
$callback
(required)


Function that prints out the HTML for the edit screen section
$post_type
(required)


The type of Write screen on which to show the edit screen
section (post, page, link or cpt)
$context
(optional)


The part of the page where the edit screen section should be
shown (normal, advanced, or side)
$priority
(optional)


The priority with the context where the boxes should show
(high, core, default, low)
$callback_args
(optional)


Arguments to pass into your callback function
Custom Meta Boxes for
Baseball Card Collection
WordPress
1. Title
2. Description
3. Featured Image
Additional Info Required
1. Sports Team
2. Card Condition
3. Is it a rookie card?
Sports Team
- use a text box



Card Condition
- use a dropdown



Rookie Card
- checkbox
Lets get started
Overview of Code
1. Add actions
2. Create custom meta box
3. Create input fields
4. Save data
// Define the custom meta box


add_action( ‘add_meta_boxes’, ‘card_meta_box’ );



// Do something with the data entered


add_action( ‘save_post’, ‘card_save_postdata’ );
// Add box to edit screen


function card_meta_box() {
    add_meta_box(
         ‘card_meta_box’, // $id
         ‘Card Details’, // $title
         ‘card_inner_custom_box’, // $callback
         ‘sports_cards_cpt’ // $post_type
    );
}
// Print the inner box contents


function card_inner_custom_box( $post ) {


    // get the post meta and display it in our input
    // the actual fields for data entry
    // use nonce for verification


}
// get the post meta and display it in our input


$team = get_post_meta($post->ID, ‘_team_name’, true);


$condition = get_post_meta($post->ID, ‘_card_condition’,
true);


$rookie = get_post_meta($post->ID, ‘_rookie_card’, true);
get_post_meta( $post_id, $key, $single);


// returns the values of the custom fields with the
specified key from the specified post
// the actual fields for data entry
// text input


<label for=”_team_name”>What team?</label>


<input type=”text” name=”_team_name” id=”_team_name” value=<?php
echo $team; ?> />
// the actual fields for data entry
// select input


<label for=”_card_condition”>What condition?</label>


<select name=”_card_condition” id=”_card_condition”>
<option value=”good” <?php selected( $condition, ‘good’ ); ?>>
   Good
</option>
<option value=”bad” <?php selected( $condition, ‘bad’ ); ?>>
   Bad
</option>
</select>
selected( $selected, $current, $echo);


// returns html (selected=‘selected’)
// replaces if/then statements
// the actual fields for data entry
// checkbox input


<input type=”checkbox” name=”_rookie_card”
id=”_rookie_card” <?php checked( $rookie, ‘on’ ); ?> />


<label for=”_rookie_card”>Is it a rookie card?</label>
checked( $checked, $current, $echo);


// returns html (checked=‘checked’)
// if values are the same, it adds checked
// use nonce for verification
// validates that the contents of the form came from the
location on the current site


wp_nonce_field( plugin_basename( __FILE__ ),
‘sports_card_nonce’ );
wp_nonce_field( $action, $name );


$action - unique identifier of nonce
$name - name of hidden form field
Output
// When the post is saved, saves our custom data


function card_save_postdata( $post ) {


    // verify it wasn’t an auto save
    // verify it came from our screen
    // check permissions
    // once authenticated, find and save the data
}
// verify is this is an autosave routine


if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE )
   return;


// verify it came from our screen with proper authorization


if ( !wp_verify_nonce( $_POST[‘sports_cards_nonce’],
plugin_basename( __FILE__) ))
   return;
// check permissions


if ( ‘page’ == $_POST[‘post_type’] ) {
    if ( !current_user_can( ‘edit_page’, $post_id ) )
           return;
} else {
    if ( !current_user_can( ‘edit_post’, $post_id ) )
       return;
}
// we’re good, find and save the data


$team = $_POST[‘_team_name’];
$condition = $_POST[‘_card_condition’];
$rookie = $_POST[‘_rookie_card’];
// add_post_meta(), update_post_meta(), custom table


if (isset($team)) {
    update_post_meta($post_id, ‘_team_name’, $team);
}
if (isset($condition)) {
    update_post_meta($post_id, ‘_card_condition’, $condition);
}
if (isset($rookie)) {
    update_post_meta($post_id, ‘_rookie_card’, $rookie);
}
update_post_meta( $post_id, $meta_key, $meta_value);


// adds post meta if it doesn’t exist
// updates post meta if a different value
How do we see our data?
Page Templates
Archives Template
Archives Template




           post meta data
// within the loop


$values = get_post_custom( $post->ID );


$team = isset( $values[‘_team_name’]) ?
   esc_attr( $values[‘_team_name’][0]) : “ “;


$condition = isset( $values[‘_card_condition’] ) ?
   esc_attr( $values[‘_card_condition’][0]) : “ “;


$rookie = isset( $values[‘_rookie_card’]) ?
   esc_attr( $values[‘_rookie_card’][0]) : “ “;
get_post_custom( $post_id);


// Returns a multidimensional array with all custom
fields of a particular post or page
<ul>
  <li>
        Team Name: <?php echo $team; ?>
  </li>
  <li>
        Condition: <?php echo $condition; ?></li>
  <li>
        Rookie Card:
        <?php echo ($rookie == “on” ? “Yes” : “No”); ?>
  </li>
</ul>
Card Details
Actions or Filters
function alt_title_change($title, $id) {


    $endo_alt_title = get_post_meta($id, '_endo_alt_title', true);


    if ($endo_alt_title && !is_admin() ) {
        $title = $endo_alt_title;
        return $title;
    }
    return $title;
}


add_filter( 'the_title', 'alt_title_change', 10, 2 );
Tips and Tricks
Use an _ to remove meta data from the
custom fields

_card_condition
Use more than one add_meta_box() if you need it on posts and pages.

add_meta_box(
     ‘card_meta_box’, // $id
     ‘Card Details’, // $title
     ‘card_inner_custom_box’, // $callback
     ‘sports_cards_cpt’ // $post_type
);


add_meta_box(
     ‘card_meta_box’, // $id
     ‘Card Details’, // $title
     ‘card_inner_custom_box’, // $callback
     ‘post’ // $post_type
);
Use delete_post_meta() to remove a
custom field

delete_post_meta($post_id, $meta_key, $meta_value);
Limit a meta box to one page by checking
post/page id

// get $post_id
$post_id = $_GET['post'] ? $_GET['post'] :$_POST['post_ID'] ;



   // checks for post/page ID

   if ($post_id == '84')

   {

   
   add_meta_box();

   }
Resources
1. Custom Metaboxes and Fields for WordPress
   - a framework for easily creating custom metaboxes
   - https://github.com/jaredatch/Custom-Metaboxes-and-
Fields-for-WordPress
2. Meta Box
   - a plugin for creating custom meta boxes
   - http://wordpress.org/extend/plugins/meta-box/
3. Reusable Custom Meta Boxes
  - http://wp.tutsplus.com/tutorials/reusable-custom-meta-
boxes-part-1-intro-and-basic-fields/
Thank You!

More Related Content

What's hot

Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Colin O'Dell
 
Drupal 8: Routing & More
Drupal 8: Routing & MoreDrupal 8: Routing & More
Drupal 8: Routing & Moredrubb
 
11. CodeIgniter vederea unei singure inregistrari
11. CodeIgniter vederea unei singure inregistrari11. CodeIgniter vederea unei singure inregistrari
11. CodeIgniter vederea unei singure inregistrariRazvan Raducanu, PhD
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
Drupal 8 Sample Module
Drupal 8 Sample ModuleDrupal 8 Sample Module
Drupal 8 Sample Moduledrubb
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Fabien Potencier
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalFredric Mitchell
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible CodeAnis Ahmad
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Fabien Potencier
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7Zsolt Tasnadi
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Fabien Potencier
 
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011Alessandro Nadalin
 

What's hot (19)

Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Framework
FrameworkFramework
Framework
 
BEAR DI
BEAR DIBEAR DI
BEAR DI
 
Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016Hacking Your Way To Better Security - Dutch PHP Conference 2016
Hacking Your Way To Better Security - Dutch PHP Conference 2016
 
Drupal 8: Routing & More
Drupal 8: Routing & MoreDrupal 8: Routing & More
Drupal 8: Routing & More
 
11. CodeIgniter vederea unei singure inregistrari
11. CodeIgniter vederea unei singure inregistrari11. CodeIgniter vederea unei singure inregistrari
11. CodeIgniter vederea unei singure inregistrari
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Drupal 8 Sample Module
Drupal 8 Sample ModuleDrupal 8 Sample Module
Drupal 8 Sample Module
 
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
 
Writing Sensible Code
Writing Sensible CodeWriting Sensible Code
Writing Sensible Code
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Entities in drupal 7
Entities in drupal 7Entities in drupal 7
Entities in drupal 7
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
Presentation1
Presentation1Presentation1
Presentation1
 
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 

Similar to WordCamp Denver 2012 - Custom Meta Boxes

laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usagePavel Makhrinsky
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Leonardo Proietti
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Abstracting functionality with centralised content
Abstracting functionality with centralised contentAbstracting functionality with centralised content
Abstracting functionality with centralised contentMichael Peacock
 
Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Dan Poltawski
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 

Similar to WordCamp Denver 2012 - Custom Meta Boxes (20)

Amp Up Your Admin
Amp Up Your AdminAmp Up Your Admin
Amp Up Your Admin
 
Zend framework 04 - forms
Zend framework 04 - formsZend framework 04 - forms
Zend framework 04 - forms
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
Moodle Quick Forms
Moodle Quick FormsMoodle Quick Forms
Moodle Quick Forms
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
dcs plus Catalogue 2015
dcs plus Catalogue 2015dcs plus Catalogue 2015
dcs plus Catalogue 2015
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
CakePHP workshop
CakePHP workshopCakePHP workshop
CakePHP workshop
 
Abstracting functionality with centralised content
Abstracting functionality with centralised contentAbstracting functionality with centralised content
Abstracting functionality with centralised content
 
Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17Moodle 3.3 - API Change Overview #mootieuk17
Moodle 3.3 - API Change Overview #mootieuk17
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 

More from Jeremy Green

Accelerated Mobile Pages - WordCamp Kansas City
Accelerated Mobile Pages - WordCamp Kansas CityAccelerated Mobile Pages - WordCamp Kansas City
Accelerated Mobile Pages - WordCamp Kansas CityJeremy Green
 
Accelerated Mobile Pages
Accelerated Mobile PagesAccelerated Mobile Pages
Accelerated Mobile PagesJeremy Green
 
The Final 20%: Improving Craftsmanship in Web Development - WordCamp DFW 2015
The Final 20%: Improving Craftsmanship in Web Development - WordCamp DFW 2015The Final 20%: Improving Craftsmanship in Web Development - WordCamp DFW 2015
The Final 20%: Improving Craftsmanship in Web Development - WordCamp DFW 2015Jeremy Green
 
You've Been Hacked, Now What? Getting WordPress Up and Running Again
You've Been Hacked, Now What? Getting WordPress Up and Running AgainYou've Been Hacked, Now What? Getting WordPress Up and Running Again
You've Been Hacked, Now What? Getting WordPress Up and Running AgainJeremy Green
 
The Final 20 Percent
The Final 20 PercentThe Final 20 Percent
The Final 20 PercentJeremy Green
 
Build a Membership Site with WordPress
Build a Membership Site with WordPressBuild a Membership Site with WordPress
Build a Membership Site with WordPressJeremy Green
 
Using Sass in Your WordPress Projects
Using Sass in Your WordPress ProjectsUsing Sass in Your WordPress Projects
Using Sass in Your WordPress ProjectsJeremy Green
 
FTP Commando to Git Hero - WordCamp Denver 2013
FTP Commando to Git Hero - WordCamp Denver 2013FTP Commando to Git Hero - WordCamp Denver 2013
FTP Commando to Git Hero - WordCamp Denver 2013Jeremy Green
 
10 Ways to Secure WordPress
10 Ways to Secure WordPress10 Ways to Secure WordPress
10 Ways to Secure WordPressJeremy Green
 

More from Jeremy Green (9)

Accelerated Mobile Pages - WordCamp Kansas City
Accelerated Mobile Pages - WordCamp Kansas CityAccelerated Mobile Pages - WordCamp Kansas City
Accelerated Mobile Pages - WordCamp Kansas City
 
Accelerated Mobile Pages
Accelerated Mobile PagesAccelerated Mobile Pages
Accelerated Mobile Pages
 
The Final 20%: Improving Craftsmanship in Web Development - WordCamp DFW 2015
The Final 20%: Improving Craftsmanship in Web Development - WordCamp DFW 2015The Final 20%: Improving Craftsmanship in Web Development - WordCamp DFW 2015
The Final 20%: Improving Craftsmanship in Web Development - WordCamp DFW 2015
 
You've Been Hacked, Now What? Getting WordPress Up and Running Again
You've Been Hacked, Now What? Getting WordPress Up and Running AgainYou've Been Hacked, Now What? Getting WordPress Up and Running Again
You've Been Hacked, Now What? Getting WordPress Up and Running Again
 
The Final 20 Percent
The Final 20 PercentThe Final 20 Percent
The Final 20 Percent
 
Build a Membership Site with WordPress
Build a Membership Site with WordPressBuild a Membership Site with WordPress
Build a Membership Site with WordPress
 
Using Sass in Your WordPress Projects
Using Sass in Your WordPress ProjectsUsing Sass in Your WordPress Projects
Using Sass in Your WordPress Projects
 
FTP Commando to Git Hero - WordCamp Denver 2013
FTP Commando to Git Hero - WordCamp Denver 2013FTP Commando to Git Hero - WordCamp Denver 2013
FTP Commando to Git Hero - WordCamp Denver 2013
 
10 Ways to Secure WordPress
10 Ways to Secure WordPress10 Ways to Secure WordPress
10 Ways to Secure WordPress
 

Recently uploaded

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Recently uploaded (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

WordCamp Denver 2012 - Custom Meta Boxes

  • 2. Jeremy Green WordPress Developer at Endo Creative Organizer of the Fort Collins WordPress Meetup @greenhornet79
  • 4. What is a custom meta box?
  • 5. It allows you to add a custom piece of data to a post or page in the administrative interface.
  • 6. What about custom fields?
  • 7. Could use custom fields, but they’re ugly and not user friendly.
  • 9. Add descriptions for users
  • 10.
  • 11. Dropdown Radio Buttons Select Text Box
  • 12. How to add a custom meta box to your plugin or theme
  • 14. $id (required) HTML ‘id’ attribute of the edit screen section
  • 15. $title (required) Title of the edit screen section, visible to the user
  • 16. $callback (required) Function that prints out the HTML for the edit screen section
  • 17. $post_type (required) The type of Write screen on which to show the edit screen section (post, page, link or cpt)
  • 18. $context (optional) The part of the page where the edit screen section should be shown (normal, advanced, or side)
  • 19. $priority (optional) The priority with the context where the boxes should show (high, core, default, low)
  • 20. $callback_args (optional) Arguments to pass into your callback function
  • 21. Custom Meta Boxes for Baseball Card Collection
  • 23. Additional Info Required 1. Sports Team 2. Card Condition 3. Is it a rookie card?
  • 24. Sports Team - use a text box Card Condition - use a dropdown Rookie Card - checkbox
  • 26. Overview of Code 1. Add actions 2. Create custom meta box 3. Create input fields 4. Save data
  • 27. // Define the custom meta box add_action( ‘add_meta_boxes’, ‘card_meta_box’ ); // Do something with the data entered add_action( ‘save_post’, ‘card_save_postdata’ );
  • 28. // Add box to edit screen function card_meta_box() { add_meta_box( ‘card_meta_box’, // $id ‘Card Details’, // $title ‘card_inner_custom_box’, // $callback ‘sports_cards_cpt’ // $post_type ); }
  • 29. // Print the inner box contents function card_inner_custom_box( $post ) { // get the post meta and display it in our input // the actual fields for data entry // use nonce for verification }
  • 30. // get the post meta and display it in our input $team = get_post_meta($post->ID, ‘_team_name’, true); $condition = get_post_meta($post->ID, ‘_card_condition’, true); $rookie = get_post_meta($post->ID, ‘_rookie_card’, true);
  • 31. get_post_meta( $post_id, $key, $single); // returns the values of the custom fields with the specified key from the specified post
  • 32. // the actual fields for data entry // text input <label for=”_team_name”>What team?</label> <input type=”text” name=”_team_name” id=”_team_name” value=<?php echo $team; ?> />
  • 33. // the actual fields for data entry // select input <label for=”_card_condition”>What condition?</label> <select name=”_card_condition” id=”_card_condition”> <option value=”good” <?php selected( $condition, ‘good’ ); ?>> Good </option> <option value=”bad” <?php selected( $condition, ‘bad’ ); ?>> Bad </option> </select>
  • 34. selected( $selected, $current, $echo); // returns html (selected=‘selected’) // replaces if/then statements
  • 35. // the actual fields for data entry // checkbox input <input type=”checkbox” name=”_rookie_card” id=”_rookie_card” <?php checked( $rookie, ‘on’ ); ?> /> <label for=”_rookie_card”>Is it a rookie card?</label>
  • 36. checked( $checked, $current, $echo); // returns html (checked=‘checked’) // if values are the same, it adds checked
  • 37. // use nonce for verification // validates that the contents of the form came from the location on the current site wp_nonce_field( plugin_basename( __FILE__ ), ‘sports_card_nonce’ );
  • 38. wp_nonce_field( $action, $name ); $action - unique identifier of nonce $name - name of hidden form field
  • 40. // When the post is saved, saves our custom data function card_save_postdata( $post ) { // verify it wasn’t an auto save // verify it came from our screen // check permissions // once authenticated, find and save the data }
  • 41. // verify is this is an autosave routine if ( defined( ‘DOING_AUTOSAVE’ ) && DOING_AUTOSAVE ) return; // verify it came from our screen with proper authorization if ( !wp_verify_nonce( $_POST[‘sports_cards_nonce’], plugin_basename( __FILE__) )) return;
  • 42. // check permissions if ( ‘page’ == $_POST[‘post_type’] ) { if ( !current_user_can( ‘edit_page’, $post_id ) ) return; } else { if ( !current_user_can( ‘edit_post’, $post_id ) ) return; }
  • 43. // we’re good, find and save the data $team = $_POST[‘_team_name’]; $condition = $_POST[‘_card_condition’]; $rookie = $_POST[‘_rookie_card’];
  • 44. // add_post_meta(), update_post_meta(), custom table if (isset($team)) { update_post_meta($post_id, ‘_team_name’, $team); } if (isset($condition)) { update_post_meta($post_id, ‘_card_condition’, $condition); } if (isset($rookie)) { update_post_meta($post_id, ‘_rookie_card’, $rookie); }
  • 45. update_post_meta( $post_id, $meta_key, $meta_value); // adds post meta if it doesn’t exist // updates post meta if a different value
  • 46. How do we see our data?
  • 49. Archives Template post meta data
  • 50. // within the loop $values = get_post_custom( $post->ID ); $team = isset( $values[‘_team_name’]) ? esc_attr( $values[‘_team_name’][0]) : “ “; $condition = isset( $values[‘_card_condition’] ) ? esc_attr( $values[‘_card_condition’][0]) : “ “; $rookie = isset( $values[‘_rookie_card’]) ? esc_attr( $values[‘_rookie_card’][0]) : “ “;
  • 51. get_post_custom( $post_id); // Returns a multidimensional array with all custom fields of a particular post or page
  • 52. <ul> <li> Team Name: <?php echo $team; ?> </li> <li> Condition: <?php echo $condition; ?></li> <li> Rookie Card: <?php echo ($rookie == “on” ? “Yes” : “No”); ?> </li> </ul>
  • 54.
  • 56. function alt_title_change($title, $id) { $endo_alt_title = get_post_meta($id, '_endo_alt_title', true); if ($endo_alt_title && !is_admin() ) { $title = $endo_alt_title; return $title; } return $title; } add_filter( 'the_title', 'alt_title_change', 10, 2 );
  • 58. Use an _ to remove meta data from the custom fields _card_condition
  • 59. Use more than one add_meta_box() if you need it on posts and pages. add_meta_box( ‘card_meta_box’, // $id ‘Card Details’, // $title ‘card_inner_custom_box’, // $callback ‘sports_cards_cpt’ // $post_type ); add_meta_box( ‘card_meta_box’, // $id ‘Card Details’, // $title ‘card_inner_custom_box’, // $callback ‘post’ // $post_type );
  • 60. Use delete_post_meta() to remove a custom field delete_post_meta($post_id, $meta_key, $meta_value);
  • 61. Limit a meta box to one page by checking post/page id // get $post_id $post_id = $_GET['post'] ? $_GET['post'] :$_POST['post_ID'] ; // checks for post/page ID if ($post_id == '84') { add_meta_box(); }
  • 63. 1. Custom Metaboxes and Fields for WordPress - a framework for easily creating custom metaboxes - https://github.com/jaredatch/Custom-Metaboxes-and- Fields-for-WordPress
  • 64. 2. Meta Box - a plugin for creating custom meta boxes - http://wordpress.org/extend/plugins/meta-box/
  • 65. 3. Reusable Custom Meta Boxes - http://wp.tutsplus.com/tutorials/reusable-custom-meta- boxes-part-1-intro-and-basic-fields/

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n