SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie Connecting Custom Post Types and Assignments in WordPress

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
 

Ähnlich wie Connecting Custom Post Types and Assignments in WordPress (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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

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
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
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
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 

Kürzlich hochgeladen (20)

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
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
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
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 

Connecting Custom Post Types and Assignments in WordPress

  • 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