SlideShare une entreprise Scribd logo
1  sur  26
CONNECTING CUSTOM
POSTTYPES
Joe Casabona
site: Casabona.org
twitter: @jcasabona
email: joe@casabona.org
slides: casabona.org/wpsummit-13
1Monday, June 10, 13
OVERVIEW
• Who am I?
• What are Custom PostTypes?
• Scope of my site
• Creating 2 types: Courses,Assignments
• Connecting them on the backend
• Connecting them on the frontend
• Planning for Grades
• Conclusion
2
2Monday, June 10, 13
WHO AM I?
• Web Developer. Writer. Nerd*.
• *Computer, Device, Star Wars
• Yankee Fan
• Author of
Building WordPress Themes from Scratch
3
3Monday, June 10, 13
WHAT ARE CUSTOM POST
TYPES?
• Any content in WordPress is considered a ‘post’
• Posts, Pages,Attachments, Revisions, Nav Menus
• Custom PostTypes (CPTs) allow us to create our own posts.
• A better name might be “Custom ContentTypes”
• Ex: Businesses, People, Job Listings, etc.
4
4Monday, June 10, 13
SCOPE OF MY SITE
• Website for my Courses
• Wanted to create an area where students could look up
Course info and Assignments
• Felt CPTs would be best
• Wanted to relate Assignments to Courses without doing it
manually
5
5Monday, June 10, 13
TIPS FOR CREATING CPTS
• Won’t go through entire development process
• For the sake of time!
• Will make these recommendations:
• Draw out CPTs before coding them.What fields do you
want and what kind of data will they hold?
• Make your CPTs a plugin, NOT part of the theme
• You don’t want to marry your theme to your content
6
6Monday, June 10, 13
CREATINGTHE COURSE CPT
• The Content:
• Title (title)
• Description (post body)
• MeetingTime (text box)
• Classroom (text box)
• Course ID/Section (text box)
• I kept it straight-forward, but would like to change a few things!
7
7Monday, June 10, 13
8
function prof_courses_register() {
$args = array(
'label' => __('Courses'),
'singular_label' => __('Course'),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'supports' => array('title', 'editor'),
'rewrite' => array('slug' => 'courses', 'with_front' =>
false),
);
register_post_type( 'courses' , $args );
}
8Monday, June 10, 13
9
$courses_meta_box = array(
'id' => 'courses-meta',
'title' => __('Course Information'),
'page' => 'courses',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => __('Meeting Times'),
'desc' => __('When the class meets'),
'id' => 'meetingtimes',
'type' => 'textarea',
'std' => ""
),
array(
'name' => __('Classroom'),
'desc' => __('Where the class meets'),
'id' => 'classroom',
'type' => 'text',
'std' => ""
),
array(
'name' => __('Course ID'),
'desc' => __('ID number of course'),
'id' => 'courseid',
'type' => 'text',
'std' => ""
),
)
);
add_action('admin_menu', 'prof_courses_meta');
9Monday, June 10, 13
10
function prof_courses_meta() {
global $courses_meta_box;
add_meta_box($courses_meta_box['id'], $courses_meta_box['title'], 'prof_course_show_meta',
$courses_meta_box['page'], $courses_meta_box['context'], $courses_meta_box['priority']);
}
// Callback function to show fields in meta box
function prof_course_show_meta() {
global $courses_meta_box, $post;
echo '<input type="hidden" name="courses_meta_box_nonce2" value="',
wp_create_nonce(basename(__FILE__)), '" />';
echo '<table class="form-table">';
foreach ($courses_meta_box['fields'] as $field) {
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
echo '<tr>',
'<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></
th>',
'<td>';
switch ($field['type']) {
case 'text':
echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="',
$meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc'];
break;
case 'textarea':
echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4"
style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc'];
break;
}
echo '<td>',
'</tr>';
}
echo '</table>';
}
10Monday, June 10, 13
11
11Monday, June 10, 13
12
12Monday, June 10, 13
CREATINGTHE ASSIGNMENT
CPT
• The Content:
• Title (title)
• Description (post body)
• Due Date (text box)
• Course (CPT: courses)
13
13Monday, June 10, 13
14
function prof_assignments_register() {
//Arguments to create post type.
$args = array(
'label' => __('Assignments'),
'singular_label' => __('Assignment'),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'supports' => array('title', 'editor', 'comments'),
'rewrite' => array('slug' => 'assignments', 'with_front' =>
false),
);
//Register type and custom taxonomy for type.
register_post_type( 'assignments' , $args );
}
14Monday, June 10, 13
15
$assignments_meta_box = array(
'id' => 'assignments-meta',
'title' => __('Assignment Information'),
'page' => 'assignments',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => __('Due Date'),
'desc' => __('When is it due?'),
'id' => 'duedate',
'type' => 'text',
'std' => ""
),
array(
'name' => __('Course'),
'desc' => __('Select the course.'),
'id' => 'course',
'type' => 'post_list',
'std' => ""
),
)
);
15Monday, June 10, 13
16
case 'post_list':
$items = get_posts( array (
'post_type' => 'courses',
'posts_per_page' => -1
));
echo '<select name="', $field['id'],'" id="'.
$field['id'],'">
<option value="">Select One</option>';
foreach($items as $item) {
echo '<option value="'.$item->ID.'"', $meta ==
$item->ID ? ' selected' : '','> '.$item->post_title.'</option>';
} // end foreach
echo '</select><br />'.$field['desc'];
break;
16Monday, June 10, 13
WHAT JUST HAPPENED?
• We essentially did created a type with a ‘foreign key’ pointing
to a different custom post type
• We will use this foreign key on the front end to grab the
assignments and display them for the selected course.
• Let’s take a look at the front end again...
17
17Monday, June 10, 13
18
18Monday, June 10, 13
DISPLAYING ASSIGNMENTS
ON COURSE PAGES
• This is a simple 2 step process:
• Get the ID of the Course we are viewing
• Select all Assignments that have that ID as the value in the
“course” custom field
• Because of the “post_list” area in the Assignments CPT, this
should be straight forward.
19
19Monday, June 10, 13
20
function prof_get_assignments($id){
$args= array(
'post_type' => 'assignments',
'meta_query' => array(
array(
'key' => 'course',
'value' => $id,
)
)
);
$assns= get_posts($args);
return $assns;
}
20Monday, June 10, 13
21
<h3>Assignments</h3>
<ul>
<?php
foreach ($assns as $a) :
$a_info= get_post_custom($a->ID);
?>
<li><a href="<?php print get_permalink($a->ID); ?>"><?php print
$a->post_title; ?></a> <strong>Due:</strong> <?php print
$a_info['duedate'][0]; ?></li>
<?php
endforeach;
?>
</ul>
location: single-courses.php
21Monday, June 10, 13
PLANNING FOR GRADES
• This complicates things!
• We need several associations
• Assignments --> Course (check)
• Grade --> Assignment
• Grade --> Student
• There are several ways to do this.
22
22Monday, June 10, 13
SOLUTION#1
• Create a Student CPT
• Include name, Student ID, any other important information
• Create a Grades CPT
• Include the grade, the Assignments Post List, the Student
Post List
• This would give us all of the information we need to derive
grades and course schedules for students
• The queries would get complicated, however.
23
23Monday, June 10, 13
SOLUTION #2
• Create only a Grades CPT
• Include grade,Assignment Post List, and name of Student.
• This would not allow for as robust reporting and would
require duplicate data entry, but it provides a quick and dirty
solution that would work.
24
24Monday, June 10, 13
WRAPPING UP
• Linking CPTs (using my method) is a 2 step process:
• On the backend, generate a list of posts and post IDs, which
will be treated as ‘foreign keys’, linking the 2 CPTs
• On the front-end, simply query your CPT, using the linked
CPT’s ID in the arguments, getting a list of all of the
associated posts.
25
25Monday, June 10, 13
QUESTIONS?
26
Live Demo
site: Casabona.org
twitter: @jcasabona
email: joe@casabona.org
slides: casabona.org/wpsummit-13
26Monday, June 10, 13

Contenu connexe

Tendances

WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...allilevine
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingChris Reynolds
 
The City Bars App with Sencha Touch 2
The City Bars App with Sencha Touch 2The City Bars App with Sencha Touch 2
The City Bars App with Sencha Touch 2James Pearce
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指すYasuo Harada
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created itPaul Bearne
 
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1Acquia
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j queryMd. Ziaul Haq
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)brockboland
 
Routing in Drupal 8
Routing in Drupal 8Routing in Drupal 8
Routing in Drupal 8kgoel1
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code OrganizationRebecca Murphey
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien 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
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?Maksym Hopei
 
Devs for Leokz e 7Masters - WTF Oriented Programming
Devs for Leokz e 7Masters - WTF Oriented ProgrammingDevs for Leokz e 7Masters - WTF Oriented Programming
Devs for Leokz e 7Masters - WTF Oriented ProgrammingFabio Akita
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Ajax nested form and ajax upload in rails
Ajax nested form and ajax upload in railsAjax nested form and ajax upload in rails
Ajax nested form and ajax upload in railsTse-Ching Ho
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In RailsLouie Zhao
 

Tendances (20)

WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
WordCamp Montreal 2015: Combining Custom Post Types, Fields, and Meta Boxes t...
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
 
The City Bars App with Sencha Touch 2
The City Bars App with Sencha Touch 2The City Bars App with Sencha Touch 2
The City Bars App with Sencha Touch 2
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指す
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created it
 
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1Drupal Step-by-Step: How We Built Our Training Site, Part 1
Drupal Step-by-Step: How We Built Our Training Site, Part 1
 
Amp Up Your Admin
Amp Up Your AdminAmp Up Your Admin
Amp Up Your Admin
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
 
Daily notes
Daily notesDaily notes
Daily notes
 
Routing in Drupal 8
Routing in Drupal 8Routing in Drupal 8
Routing in Drupal 8
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
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
 
How else can you write the code in PHP?
How else can you write the code in PHP?How else can you write the code in PHP?
How else can you write the code in PHP?
 
Devs for Leokz e 7Masters - WTF Oriented Programming
Devs for Leokz e 7Masters - WTF Oriented ProgrammingDevs for Leokz e 7Masters - WTF Oriented Programming
Devs for Leokz e 7Masters - WTF Oriented Programming
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Postgresql and ror
Postgresql and rorPostgresql and ror
Postgresql and ror
 
Ajax nested form and ajax upload in rails
Ajax nested form and ajax upload in railsAjax nested form and ajax upload in rails
Ajax nested form and ajax upload in rails
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In Rails
 

En vedette

The Dean wants to Make this WordPress Site Responsive
The Dean wants to Make this WordPress Site ResponsiveThe Dean wants to Make this WordPress Site Responsive
The Dean wants to Make this WordPress Site ResponsiveJoe Casabona
 
Wearable Technology: The Next Big Thing
Wearable Technology: The Next Big ThingWearable Technology: The Next Big Thing
Wearable Technology: The Next Big ThingJoe Casabona
 
Responsive Design with WordPress (WCPHX)
Responsive Design with WordPress (WCPHX)Responsive Design with WordPress (WCPHX)
Responsive Design with WordPress (WCPHX)Joe Casabona
 
Building Parsec : The Planning Stage
Building Parsec : The Planning StageBuilding Parsec : The Planning Stage
Building Parsec : The Planning StageJoe Casabona
 
My Top WordPress Plugins
My Top WordPress PluginsMy Top WordPress Plugins
My Top WordPress PluginsJoe Casabona
 
Using PHP to Create a Web Based Mobile Banner Application
Using PHP to Create a Web Based Mobile Banner ApplicationUsing PHP to Create a Web Based Mobile Banner Application
Using PHP to Create a Web Based Mobile Banner ApplicationJoe Casabona
 

En vedette (6)

The Dean wants to Make this WordPress Site Responsive
The Dean wants to Make this WordPress Site ResponsiveThe Dean wants to Make this WordPress Site Responsive
The Dean wants to Make this WordPress Site Responsive
 
Wearable Technology: The Next Big Thing
Wearable Technology: The Next Big ThingWearable Technology: The Next Big Thing
Wearable Technology: The Next Big Thing
 
Responsive Design with WordPress (WCPHX)
Responsive Design with WordPress (WCPHX)Responsive Design with WordPress (WCPHX)
Responsive Design with WordPress (WCPHX)
 
Building Parsec : The Planning Stage
Building Parsec : The Planning StageBuilding Parsec : The Planning Stage
Building Parsec : The Planning Stage
 
My Top WordPress Plugins
My Top WordPress PluginsMy Top WordPress Plugins
My Top WordPress Plugins
 
Using PHP to Create a Web Based Mobile Banner Application
Using PHP to Create a Web Based Mobile Banner ApplicationUsing PHP to Create a Web Based Mobile Banner Application
Using PHP to Create a Web Based Mobile Banner Application
 

Similaire à Connecting Custom Post Types

Beyond Posts & Pages - Structured Content in WordPress
Beyond Posts & Pages - Structured Content in WordPressBeyond Posts & Pages - Structured Content in WordPress
Beyond Posts & Pages - Structured Content in WordPressJohn Eckman
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoMohamed Mosaad
 
次世代版 PowerCMS 開発プロジェクトのご紹介
次世代版 PowerCMS 開発プロジェクトのご紹介次世代版 PowerCMS 開発プロジェクトのご紹介
次世代版 PowerCMS 開発プロジェクトのご紹介純生 野田
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
Custom Post Types and Meta Fields
Custom Post Types and Meta FieldsCustom Post Types and Meta Fields
Custom Post Types and Meta FieldsLiton Arefin
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodJeremy Kendall
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesJeremy Green
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 

Similaire à Connecting Custom Post Types (20)

Beyond Posts & Pages - Structured Content in WordPress
Beyond Posts & Pages - Structured Content in WordPressBeyond Posts & Pages - Structured Content in WordPress
Beyond Posts & Pages - Structured Content in WordPress
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
次世代版 PowerCMS 開発プロジェクトのご紹介
次世代版 PowerCMS 開発プロジェクトのご紹介次世代版 PowerCMS 開発プロジェクトのご紹介
次世代版 PowerCMS 開発プロジェクトのご紹介
 
PowerCMS X
PowerCMS XPowerCMS X
PowerCMS X
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Custom Post Types and Meta Fields
Custom Post Types and Meta FieldsCustom Post Types and Meta Fields
Custom Post Types and Meta Fields
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
 
WordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta BoxesWordCamp Denver 2012 - Custom Meta Boxes
WordCamp Denver 2012 - Custom Meta Boxes
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 

Plus de Joe Casabona

Local Development Environments
Local Development EnvironmentsLocal Development Environments
Local Development EnvironmentsJoe Casabona
 
WCCHS: Responsive Design with WordPress
WCCHS: Responsive Design with WordPressWCCHS: Responsive Design with WordPress
WCCHS: Responsive Design with WordPressJoe Casabona
 
Responsive Design with WordPress
Responsive Design with WordPressResponsive Design with WordPress
Responsive Design with WordPressJoe Casabona
 
Hacking the Luminis 5 Portal
Hacking the Luminis 5 PortalHacking the Luminis 5 Portal
Hacking the Luminis 5 PortalJoe Casabona
 
WordPress Customization and Security
WordPress Customization and SecurityWordPress Customization and Security
WordPress Customization and SecurityJoe Casabona
 
Building a Simple Theme Framework
Building a Simple Theme FrameworkBuilding a Simple Theme Framework
Building a Simple Theme FrameworkJoe Casabona
 

Plus de Joe Casabona (6)

Local Development Environments
Local Development EnvironmentsLocal Development Environments
Local Development Environments
 
WCCHS: Responsive Design with WordPress
WCCHS: Responsive Design with WordPressWCCHS: Responsive Design with WordPress
WCCHS: Responsive Design with WordPress
 
Responsive Design with WordPress
Responsive Design with WordPressResponsive Design with WordPress
Responsive Design with WordPress
 
Hacking the Luminis 5 Portal
Hacking the Luminis 5 PortalHacking the Luminis 5 Portal
Hacking the Luminis 5 Portal
 
WordPress Customization and Security
WordPress Customization and SecurityWordPress Customization and Security
WordPress Customization and Security
 
Building a Simple Theme Framework
Building a Simple Theme FrameworkBuilding a Simple Theme Framework
Building a Simple Theme Framework
 

Dernier

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
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
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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
 
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
 
[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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
🐬 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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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
 
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
 
[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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Connecting Custom Post Types

  • 1. CONNECTING CUSTOM POSTTYPES Joe Casabona site: Casabona.org twitter: @jcasabona email: joe@casabona.org slides: casabona.org/wpsummit-13 1Monday, June 10, 13
  • 2. OVERVIEW • Who am I? • What are Custom PostTypes? • Scope of my site • Creating 2 types: Courses,Assignments • Connecting them on the backend • Connecting them on the frontend • Planning for Grades • Conclusion 2 2Monday, June 10, 13
  • 3. WHO AM I? • Web Developer. Writer. Nerd*. • *Computer, Device, Star Wars • Yankee Fan • Author of Building WordPress Themes from Scratch 3 3Monday, June 10, 13
  • 4. WHAT ARE CUSTOM POST TYPES? • Any content in WordPress is considered a ‘post’ • Posts, Pages,Attachments, Revisions, Nav Menus • Custom PostTypes (CPTs) allow us to create our own posts. • A better name might be “Custom ContentTypes” • Ex: Businesses, People, Job Listings, etc. 4 4Monday, June 10, 13
  • 5. SCOPE OF MY SITE • Website for my Courses • Wanted to create an area where students could look up Course info and Assignments • Felt CPTs would be best • Wanted to relate Assignments to Courses without doing it manually 5 5Monday, June 10, 13
  • 6. TIPS FOR CREATING CPTS • Won’t go through entire development process • For the sake of time! • Will make these recommendations: • Draw out CPTs before coding them.What fields do you want and what kind of data will they hold? • Make your CPTs a plugin, NOT part of the theme • You don’t want to marry your theme to your content 6 6Monday, June 10, 13
  • 7. CREATINGTHE COURSE CPT • The Content: • Title (title) • Description (post body) • MeetingTime (text box) • Classroom (text box) • Course ID/Section (text box) • I kept it straight-forward, but would like to change a few things! 7 7Monday, June 10, 13
  • 8. 8 function prof_courses_register() { $args = array( 'label' => __('Courses'), 'singular_label' => __('Course'), 'public' => true, 'show_ui' => true, 'capability_type' => 'post', 'hierarchical' => true, 'has_archive' => true, 'supports' => array('title', 'editor'), 'rewrite' => array('slug' => 'courses', 'with_front' => false), ); register_post_type( 'courses' , $args ); } 8Monday, June 10, 13
  • 9. 9 $courses_meta_box = array( 'id' => 'courses-meta', 'title' => __('Course Information'), 'page' => 'courses', 'context' => 'normal', 'priority' => 'high', 'fields' => array( array( 'name' => __('Meeting Times'), 'desc' => __('When the class meets'), 'id' => 'meetingtimes', 'type' => 'textarea', 'std' => "" ), array( 'name' => __('Classroom'), 'desc' => __('Where the class meets'), 'id' => 'classroom', 'type' => 'text', 'std' => "" ), array( 'name' => __('Course ID'), 'desc' => __('ID number of course'), 'id' => 'courseid', 'type' => 'text', 'std' => "" ), ) ); add_action('admin_menu', 'prof_courses_meta'); 9Monday, June 10, 13
  • 10. 10 function prof_courses_meta() { global $courses_meta_box; add_meta_box($courses_meta_box['id'], $courses_meta_box['title'], 'prof_course_show_meta', $courses_meta_box['page'], $courses_meta_box['context'], $courses_meta_box['priority']); } // Callback function to show fields in meta box function prof_course_show_meta() { global $courses_meta_box, $post; echo '<input type="hidden" name="courses_meta_box_nonce2" value="', wp_create_nonce(basename(__FILE__)), '" />'; echo '<table class="form-table">'; foreach ($courses_meta_box['fields'] as $field) { // get current post meta data $meta = get_post_meta($post->ID, $field['id'], true); echo '<tr>', '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></ th>', '<td>'; switch ($field['type']) { case 'text': echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc']; break; case 'textarea': echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc']; break; } echo '<td>', '</tr>'; } echo '</table>'; } 10Monday, June 10, 13
  • 13. CREATINGTHE ASSIGNMENT CPT • The Content: • Title (title) • Description (post body) • Due Date (text box) • Course (CPT: courses) 13 13Monday, June 10, 13
  • 14. 14 function prof_assignments_register() { //Arguments to create post type. $args = array( 'label' => __('Assignments'), 'singular_label' => __('Assignment'), 'public' => true, 'show_ui' => true, 'capability_type' => 'post', 'hierarchical' => true, 'has_archive' => true, 'supports' => array('title', 'editor', 'comments'), 'rewrite' => array('slug' => 'assignments', 'with_front' => false), ); //Register type and custom taxonomy for type. register_post_type( 'assignments' , $args ); } 14Monday, June 10, 13
  • 15. 15 $assignments_meta_box = array( 'id' => 'assignments-meta', 'title' => __('Assignment Information'), 'page' => 'assignments', 'context' => 'normal', 'priority' => 'high', 'fields' => array( array( 'name' => __('Due Date'), 'desc' => __('When is it due?'), 'id' => 'duedate', 'type' => 'text', 'std' => "" ), array( 'name' => __('Course'), 'desc' => __('Select the course.'), 'id' => 'course', 'type' => 'post_list', 'std' => "" ), ) ); 15Monday, June 10, 13
  • 16. 16 case 'post_list': $items = get_posts( array ( 'post_type' => 'courses', 'posts_per_page' => -1 )); echo '<select name="', $field['id'],'" id="'. $field['id'],'"> <option value="">Select One</option>'; foreach($items as $item) { echo '<option value="'.$item->ID.'"', $meta == $item->ID ? ' selected' : '','> '.$item->post_title.'</option>'; } // end foreach echo '</select><br />'.$field['desc']; break; 16Monday, June 10, 13
  • 17. WHAT JUST HAPPENED? • We essentially did created a type with a ‘foreign key’ pointing to a different custom post type • We will use this foreign key on the front end to grab the assignments and display them for the selected course. • Let’s take a look at the front end again... 17 17Monday, June 10, 13
  • 19. DISPLAYING ASSIGNMENTS ON COURSE PAGES • This is a simple 2 step process: • Get the ID of the Course we are viewing • Select all Assignments that have that ID as the value in the “course” custom field • Because of the “post_list” area in the Assignments CPT, this should be straight forward. 19 19Monday, June 10, 13
  • 20. 20 function prof_get_assignments($id){ $args= array( 'post_type' => 'assignments', 'meta_query' => array( array( 'key' => 'course', 'value' => $id, ) ) ); $assns= get_posts($args); return $assns; } 20Monday, June 10, 13
  • 21. 21 <h3>Assignments</h3> <ul> <?php foreach ($assns as $a) : $a_info= get_post_custom($a->ID); ?> <li><a href="<?php print get_permalink($a->ID); ?>"><?php print $a->post_title; ?></a> <strong>Due:</strong> <?php print $a_info['duedate'][0]; ?></li> <?php endforeach; ?> </ul> location: single-courses.php 21Monday, June 10, 13
  • 22. PLANNING FOR GRADES • This complicates things! • We need several associations • Assignments --> Course (check) • Grade --> Assignment • Grade --> Student • There are several ways to do this. 22 22Monday, June 10, 13
  • 23. SOLUTION#1 • Create a Student CPT • Include name, Student ID, any other important information • Create a Grades CPT • Include the grade, the Assignments Post List, the Student Post List • This would give us all of the information we need to derive grades and course schedules for students • The queries would get complicated, however. 23 23Monday, June 10, 13
  • 24. SOLUTION #2 • Create only a Grades CPT • Include grade,Assignment Post List, and name of Student. • This would not allow for as robust reporting and would require duplicate data entry, but it provides a quick and dirty solution that would work. 24 24Monday, June 10, 13
  • 25. WRAPPING UP • Linking CPTs (using my method) is a 2 step process: • On the backend, generate a list of posts and post IDs, which will be treated as ‘foreign keys’, linking the 2 CPTs • On the front-end, simply query your CPT, using the linked CPT’s ID in the arguments, getting a list of all of the associated posts. 25 25Monday, June 10, 13
  • 26. QUESTIONS? 26 Live Demo site: Casabona.org twitter: @jcasabona email: joe@casabona.org slides: casabona.org/wpsummit-13 26Monday, June 10, 13