SlideShare une entreprise Scribd logo
1  sur  34
Custom Posts and Meta Boxes
About Me
Md. Liton Arefin
Senior Developer
JoomShaper
What is Post Type?
WordPress can hold and display many different types of content. A
single item of such a content is generally called a post, post is also
a specific post type.
Custom Post Types
• Post
• Page
• Attachment
• Revision
• Navigation
Where Post Type Locates?
• Post type stored in “wp_posts” database table
When Custom Post Type Needs?
• If you need to Develop websites like:
• www.youtube.com
• www.bbc.co.uk
Etc
• Most Used Custom Post Type and Meta
Fields
• Geo Theme (http://www.geotheme.com)
When Custom Post Type Needs?
When Websites Contains:
• Homepage Slider
• Callout Boxes
• Portfolio
• Gallery (Image, Video etc)
• Team/People/Staff
• Job Posting
• Products
• Pricing Table
• etc
Example
Example
What we need to create a Portfolio?
What we need to create a Portfolio?
• Title
• Custom Field (Website Address)
• Content
• Thumbnail Image
• Taxonomy Category/Tags
Register Custom Post Type
 register_post_type is called when you need to create or modify
a post_type. register_post_type should only be invoked
through the ‘init’ action.
Reference
http://codex.wordpress.org/Function_Reference/register_post_type
Reserved Post Types
• post
• page
• attactment
• revision
• nav_menu_item
<?php register_post_type( $post_type, $args ) ?>
Practical Example
function sp_portfolio() {
$labels = array( 'name' => _x( 'Portfolio', 'post type general name' ),
'singular_name' => _x( 'Portfolio', 'post type singular name' ),
'add_new' => _x( 'Add New', 'book' ),
'add_new_item' => __( 'Add New Portfolio' ),
'edit_item' => __( 'Edit Portfolio' ),
'new_item' => __( 'New Portfolio Items' ),
'all_items' => __( 'All Portfolio' ),
'view_item' => __( 'View Portfolio' ),
'search_items' => __( 'Search Portfolio' ),
'not_found' => __( 'No Portfolio Items found' ),
'not_found_in_trash' => __( 'No Portfolio Items found in the Trash' ),
'parent_item_colon' => '',
'menu_name' => 'SP Portfolio' );
);
$args = array( 'labels' => $labels,
'description' => 'Holds Portfolio specific data',
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'portfolio/%year%',
'with_front' => true),
'capability_type'=> 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 5,
'supports' => array( 'title', 'editor', 'thumbnail'),
'menu_icon' => plugins_url( 'images/icon1.png', __FILE__ ) // Icon Path
);
register_post_type( 'portfolio', $args );
Output Of register_post_type()
Register Taxonomy
Reference:
http://codex.wordpress.org/Function_Reference/register_taxonomy
<?php register_taxonomy( $taxonomy, $object_type, $args ); ?>
// Custom Portfolio Categories
$labels = array('name' => _x( 'Categories', 'taxonomy general name' ),
'singular_name' => _x( 'SP Category', 'taxonomy singular name' ),
'search_items' => __( 'Search Types' ),
'all_items' => __( 'All Categories' ),
'parent_item' => __( 'Parent Category' ),
'parent_item_colon' => __( 'Parent Category:' ),
'edit_item' => __( 'Edit Category' ),
'update_item' => __( 'Update Category' ),
'add_new_item' => __( 'Add New Category' ),
'new_item_name' => __( 'New Category Name' ),
); // Custom taxonomy for Project Tags
register_taxonomy('sptag', array('portfolio'),
array(
'hierarchical' => true,
'labels' => $labels,
'show_ui' => true,
'query_var' => true,
'rewrite' =>true,
));
}
add_action( 'init', 'sp_portfolio' );
Meta Box field for Custom Post Type
Reference:
http://codex.wordpress.org/Function_Reference/add_meta_box
<?php   add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args ); ?>
add_action('admin_init','sp_portfolio_meta');
function sp_portfolio_meta() {
// add a meta box for WordPress 'project' type
add_meta_box('sp_portfolio', 'Portfolio URL', 'sp_portfolio_meta_setup', 'portfolio', 'side', 'low');         
// add a callback function to save any data a user enters in
add_action('save_post','sp_portfolio_meta_save');  
}
function sp_portfolio_meta_setup() {
global $post;
?>
<div class="portfolio_meta_control">
<p>
<input type="text" name="_url" value="<?php echo get_post_meta($post->ID,'_url',TRUE); ?>" style="width: 100%;" />
</p>
</div>
<?php
// create for validation
echo '<input type="hidden" name="sp_meta_nonce" value="' . wp_create_nonce(__FILE__) . '" />';
}
function sp_portfolio_meta_save($post_id) {
// check nonce
if (!isset($_POST['sp_meta_nonce']) || !wp_verify_nonce($_POST['sp_meta_nonce'], __FILE__))
{ return $post_id;
}
// check capabilities
if (portfolio' == $_POST[post_type']) {
if (!current_user_can('edit_post', $post_id)) {
return $post_id; } } elseif (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
// exit on autosave
if (defined('DOING_AUTOSAVE') == DOING_AUTOSAVE) {
return $post_id;
}
if(isset($_POST['_url'])) {
update_post_meta($post_id, '_url', $_POST['_url']); } else {
delete_post_meta($post_id, '_url');
}
About Nonces:
http://codex.wordpress.org/Function_Reference/wp_create_nonce
Manage Custom Post Columns
function sp_add_columns($cols) {
$cols['title'] = __('Portfolio Title');
$cols['thumbnail'] = __('Thumbnail');
$cols['description'] =__('Description');
$cols['_url'] =__('Portfolio URL');
$cols['sptag'] = __('Categories');
//Unset Default Date, Author etc
unset  ($cols['date'],
$cols['author']);
return $cols;
}
function sp_add_column_values($column_name, $post_id) {
$width = (int) 100; $height = (int) 100;
if ( 'thumbnail' == $column_name ) {
$thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
// image from gallery
$attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'portfolio',
'post_mime_type' => 'image') );
if ($thumbnail_id)
$thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true ); elseif
($attachments) {
foreach ( $attachments as $attachment_id => $attachment ) {
$thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
}
} if ( isset($thumb) && $thumb ) {
echo $thumb;
} else {
echo __('None');
}}
elseif ('description' == $column_name) {
echo the_content();
} elseif ('_url' == $column_name) {
echo get_post_meta($post_id, '_url', true);
} elseif ('sptag' == $column_name) {
$terms = wp_get_post_terms(get_the_ID(), 'sptag' );
$t = array();
foreach($terms as $term) $t[] = $term->slug;
echo implode(', ', $t);
$t = array();
}
}
// For Portfolio Items
add_filter( 'manage_portfolio_posts_columns', 'sp_add_columns' );
add_action( 'manage_portfolio_posts_custom_column', 'sp_add_column_values', 10, 2 );
Reference:
http://codex.wordpress.org/Plugin_API/Filter_Reference/manage_$post_type_posts_columns
http://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column
http://codex.wordpress.org/Plugin_API/Filter_Reference/manage_edit-post_type_columns
http://justintadlock.com/archives/2011/06/27/custom-columns-for-custom-post-types
How to show Contents?
There are few options to retrieve custom posts
query_posts()
WP_Query()
get_posts()
Refefences:
http://codex.wordpress.org/Function_Reference/query_posts
http://codex.wordpress.org/Class_Reference/WP_Query
http://codex.wordpress.org/Template_Tags/get_posts
Query_posts()
<?php
/*
* Template Name: SP Portfolio
*/
get_header();
query_posts(array('post_type' => 'portfolio', 'posts_per_page' => -1));
?>
<div class=“container”>
<?php if(have_posts()){ while(have_posts()){ the_post(); ?>
<article class=“post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><?php the_title();?></h2>
<p><?php the_content();?></p>
<a href=“<?php echo get_post_meta($post->ID, '_url', true); ?>”></a>
</article>
<?php } }
// Reset Query
wp_reset_query();
?>
</div>
<?php get_footer();?>
WP_Query()
<?php
/*
* Template Name: SP Portfolio
*/
get_header();
$args = array('post_type' => 'portfolio', 'posts_per_page' => -1);
$query = new WP_Query( $args );
?>
<div class=“container”>
<?php if($query->have_posts()){ while($query->have_posts()){$query->the_post(); ?>
<article class=“post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><?php echo get_the_title();?></h2>
<p><?php echo get_the_content();?></p>
<a href=“<?php echo get_post_meta($post->ID, '_url', true); ?>”></a>
</article>
<?php } }
// Restore original Post Data
wp_reset_postdata();
?>
</div>
<?php get_footer();?>
get_posts()
<?php
/*
* Template Name: SP Portfolio
*/
get_header();
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 );
$query = get_posts( $args );
foreach ( $query as $post ) { setup_postdata( $post );
?>
<div class=“container”>
<article class=“post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </h2>
<p><?php the_content();?></p>
<a href=“<?php echo get_post_meta($post->ID, '_url', true); ?>”></a>
</article>
<?php
}
// Restore original Post Data
wp_reset_postdata();
?>
</div>
<?php get_footer();?>
Which one is best?
query_posts() : alter of main query. Post-related
global variables and template tags will be altered.
 WP_Query() : defined in wp-includes/query.php.
wp-blog-header.php gives $wp_query object
information. $is_* holds the informations.
get_posts() : returns array of posts. Direct access
to database using WP_Query()
get_posts() is best to use.
Page Template
function sp_template_redirect($template_path ) {
if ('portfolio' == $_POST['post_type']) {
$template_path = plugin_dir_path( __FILE__ ) . '/theme/page-portfolio.php';
}
return $template_path;
}
add_action(‘template_redirect’,’ sp_template_redirect’);
You should use
For secondary query like sidebar widget posts
use WP_Query or get_posts()
References
• http://generatewp.com/
• http://www.joomshaper.com/blog/wordpress/create-a-custom-post-type-in-wordpress
• http://www.joomshaper.com/blog/wordpress/add-meta-boxes-in-custom-post-type
• http://wp.smashingmagazine.com/2012/11/08/complete-guide-custom-post-types/
• http://wp.tutsplus.com/tutorials/plugins/a-guide-to-wordpress-custom-post-types-creation-
display-and-meta-boxes/
• http://wp.tutsplus.com/tutorials/creative-coding/custom-page-template-page-based-on-url-
rewrite/
• http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-the-basics/
• http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-post-types-taxonomies/
Thanks
Question ???

Contenu connexe

Tendances

Introduction to Zend_Pdf
Introduction to Zend_PdfIntroduction to Zend_Pdf
Introduction to Zend_Pdfdennisdc
 
Custom content types &amp; custom taxonomies in wordpress
Custom content types &amp; custom taxonomies in wordpressCustom content types &amp; custom taxonomies in wordpress
Custom content types &amp; custom taxonomies in wordpressstimasoft
 
Introduction to ZendX jQuery
Introduction to ZendX jQueryIntroduction to ZendX jQuery
Introduction to ZendX jQuerydennisdc
 
Building a Portfolio With Custom Post Types
Building a Portfolio With Custom Post TypesBuilding a Portfolio With Custom Post Types
Building a Portfolio With Custom Post TypesAlex Blackie
 
Shortcodes In-Depth
Shortcodes In-DepthShortcodes In-Depth
Shortcodes In-DepthMicah Wood
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Balázs Tatár
 
Twitter bootstrap
Twitter bootstrapTwitter bootstrap
Twitter bootstrapdennisdc
 
You're Doing it Wrong - WordCamp Atlanta
You're Doing it Wrong - WordCamp AtlantaYou're Doing it Wrong - WordCamp Atlanta
You're Doing it Wrong - WordCamp AtlantaChris Scott
 
Make your own wp cli command in 10min
Make your own wp cli command in 10minMake your own wp cli command in 10min
Make your own wp cli command in 10minIvelina Dimova
 
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Atwix
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Balázs Tatár
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011Maurizio Pelizzone
 
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019Balázs Tatár
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Balázs Tatár
 
Clever Joomla! Templating Tips and Tricks
Clever Joomla! Templating Tips and TricksClever Joomla! Templating Tips and Tricks
Clever Joomla! Templating Tips and TricksThemePartner
 

Tendances (20)

Introduction to Zend_Pdf
Introduction to Zend_PdfIntroduction to Zend_Pdf
Introduction to Zend_Pdf
 
logic321
logic321logic321
logic321
 
Custom content types &amp; custom taxonomies in wordpress
Custom content types &amp; custom taxonomies in wordpressCustom content types &amp; custom taxonomies in wordpress
Custom content types &amp; custom taxonomies in wordpress
 
Introduction to ZendX jQuery
Introduction to ZendX jQueryIntroduction to ZendX jQuery
Introduction to ZendX jQuery
 
Building a Portfolio With Custom Post Types
Building a Portfolio With Custom Post TypesBuilding a Portfolio With Custom Post Types
Building a Portfolio With Custom Post Types
 
Shortcodes In-Depth
Shortcodes In-DepthShortcodes In-Depth
Shortcodes In-Depth
 
Wp meetup custom post types
Wp meetup custom post typesWp meetup custom post types
Wp meetup custom post types
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
 
Twitter bootstrap
Twitter bootstrapTwitter bootstrap
Twitter bootstrap
 
JQuery Basics
JQuery BasicsJQuery Basics
JQuery Basics
 
You're Doing it Wrong - WordCamp Atlanta
You're Doing it Wrong - WordCamp AtlantaYou're Doing it Wrong - WordCamp Atlanta
You're Doing it Wrong - WordCamp Atlanta
 
Mobile themes, QR codes, and shortURLs
Mobile themes, QR codes, and shortURLsMobile themes, QR codes, and shortURLs
Mobile themes, QR codes, and shortURLs
 
Make your own wp cli command in 10min
Make your own wp cli command in 10minMake your own wp cli command in 10min
Make your own wp cli command in 10min
 
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
 
Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019Let's write secure Drupal code! - Drupal Camp Poland 2019
Let's write secure Drupal code! - Drupal Camp Poland 2019
 
WordPress for developers - phpday 2011
WordPress for developers -  phpday 2011WordPress for developers -  phpday 2011
WordPress for developers - phpday 2011
 
Daily notes
Daily notesDaily notes
Daily notes
 
Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019Let's write secure drupal code! - Drupal Camp Pannonia 2019
Let's write secure drupal code! - Drupal Camp Pannonia 2019
 
Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019Let's write secure Drupal code! DUG Belgium - 08/08/2019
Let's write secure Drupal code! DUG Belgium - 08/08/2019
 
Clever Joomla! Templating Tips and Tricks
Clever Joomla! Templating Tips and TricksClever Joomla! Templating Tips and Tricks
Clever Joomla! Templating Tips and Tricks
 

En vedette

WordPress and E-Commerce
WordPress and E-CommerceWordPress and E-Commerce
WordPress and E-Commercesprclldr
 
WordPress Freelancing
WordPress FreelancingWordPress Freelancing
WordPress Freelancingsprclldr
 
Computerand mother board parts and fungations
Computerand mother board  parts and fungationsComputerand mother board  parts and fungations
Computerand mother board parts and fungationsRockmanju
 
Custom Post Types and Taxonomies in WordPress
Custom Post Types and Taxonomies in WordPressCustom Post Types and Taxonomies in WordPress
Custom Post Types and Taxonomies in WordPressBrad Williams
 
Categories, Tags, Custom Post Types! Oh My!
Categories, Tags, Custom Post Types! Oh My!Categories, Tags, Custom Post Types! Oh My!
Categories, Tags, Custom Post Types! Oh My!sprclldr
 
Entry-level PHP for WordPress
Entry-level PHP for WordPressEntry-level PHP for WordPress
Entry-level PHP for WordPresssprclldr
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome EconomyHelge Tennø
 

En vedette (7)

WordPress and E-Commerce
WordPress and E-CommerceWordPress and E-Commerce
WordPress and E-Commerce
 
WordPress Freelancing
WordPress FreelancingWordPress Freelancing
WordPress Freelancing
 
Computerand mother board parts and fungations
Computerand mother board  parts and fungationsComputerand mother board  parts and fungations
Computerand mother board parts and fungations
 
Custom Post Types and Taxonomies in WordPress
Custom Post Types and Taxonomies in WordPressCustom Post Types and Taxonomies in WordPress
Custom Post Types and Taxonomies in WordPress
 
Categories, Tags, Custom Post Types! Oh My!
Categories, Tags, Custom Post Types! Oh My!Categories, Tags, Custom Post Types! Oh My!
Categories, Tags, Custom Post Types! Oh My!
 
Entry-level PHP for WordPress
Entry-level PHP for WordPressEntry-level PHP for WordPress
Entry-level PHP for WordPress
 
The Outcome Economy
The Outcome EconomyThe Outcome Economy
The Outcome Economy
 

Similaire à Custom Post Types and Meta Fields

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
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress WebsitesKyle Cearley
 
Abstracting functionality with centralised content
Abstracting functionality with centralised contentAbstracting functionality with centralised content
Abstracting functionality with centralised contentMichael Peacock
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)tompunk
 
PSD to WordPress
PSD to WordPressPSD to WordPress
PSD to WordPressNile Flores
 
Extending WordPress. Making use of Custom Post Types
Extending WordPress. Making use of Custom Post TypesExtending WordPress. Making use of Custom Post Types
Extending WordPress. Making use of Custom Post TypesUtsav Singh Rathour
 
Various Ways of Using WordPress
Various Ways of Using WordPressVarious Ways of Using WordPress
Various Ways of Using WordPressNick La
 
The Way to Theme Enlightenment
The Way to Theme EnlightenmentThe Way to Theme Enlightenment
The Way to Theme EnlightenmentAmanda Giles
 
WordPress Queries - the right way
WordPress Queries - the right wayWordPress Queries - the right way
WordPress Queries - the right wayAnthony Hortin
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018Adam Tomat
 
How to make a WordPress theme
How to make a WordPress themeHow to make a WordPress theme
How to make a WordPress themeHardeep Asrani
 
You're Doing it Wrong - WordCamp Orlando
You're Doing it Wrong - WordCamp OrlandoYou're Doing it Wrong - WordCamp Orlando
You're Doing it Wrong - WordCamp OrlandoChris Scott
 
WordPress 3.4 Theme Customizer
WordPress 3.4 Theme CustomizerWordPress 3.4 Theme Customizer
WordPress 3.4 Theme CustomizerChandra Maharzan
 
Can WordPress really do that? A case study of vierderduer.no
Can WordPress really do that? A case study of vierderduer.noCan WordPress really do that? A case study of vierderduer.no
Can WordPress really do that? A case study of vierderduer.noMorten Rand-Hendriksen
 
Creatively creating custom post types!
Creatively creating custom post types!Creatively creating custom post types!
Creatively creating custom post types!techvoltz
 
Creatively creating custom post types!
Creatively creating custom post types!Creatively creating custom post types!
Creatively creating custom post types!techvoltz
 

Similaire à Custom Post Types and Meta Fields (20)

20110820 header new style
20110820 header new style20110820 header new style
20110820 header new style
 
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
 
Building Potent WordPress Websites
Building Potent WordPress WebsitesBuilding Potent WordPress Websites
Building Potent WordPress Websites
 
Abstracting functionality with centralised content
Abstracting functionality with centralised contentAbstracting functionality with centralised content
Abstracting functionality with centralised content
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 
PSD to WordPress
PSD to WordPressPSD to WordPress
PSD to WordPress
 
Extending WordPress. Making use of Custom Post Types
Extending WordPress. Making use of Custom Post TypesExtending WordPress. Making use of Custom Post Types
Extending WordPress. Making use of Custom Post Types
 
Various Ways of Using WordPress
Various Ways of Using WordPressVarious Ways of Using WordPress
Various Ways of Using WordPress
 
The Way to Theme Enlightenment
The Way to Theme EnlightenmentThe Way to Theme Enlightenment
The Way to Theme Enlightenment
 
WordPress Queries - the right way
WordPress Queries - the right wayWordPress Queries - the right way
WordPress Queries - the right way
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 
Django
DjangoDjango
Django
 
How to make a WordPress theme
How to make a WordPress themeHow to make a WordPress theme
How to make a WordPress theme
 
Blog Hacks 2011
Blog Hacks 2011Blog Hacks 2011
Blog Hacks 2011
 
You're Doing it Wrong - WordCamp Orlando
You're Doing it Wrong - WordCamp OrlandoYou're Doing it Wrong - WordCamp Orlando
You're Doing it Wrong - WordCamp Orlando
 
Word Camp Fukuoka2010
Word Camp Fukuoka2010Word Camp Fukuoka2010
Word Camp Fukuoka2010
 
WordPress 3.4 Theme Customizer
WordPress 3.4 Theme CustomizerWordPress 3.4 Theme Customizer
WordPress 3.4 Theme Customizer
 
Can WordPress really do that? A case study of vierderduer.no
Can WordPress really do that? A case study of vierderduer.noCan WordPress really do that? A case study of vierderduer.no
Can WordPress really do that? A case study of vierderduer.no
 
Creatively creating custom post types!
Creatively creating custom post types!Creatively creating custom post types!
Creatively creating custom post types!
 
Creatively creating custom post types!
Creatively creating custom post types!Creatively creating custom post types!
Creatively creating custom post types!
 

Dernier

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 

Dernier (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 

Custom Post Types and Meta Fields

  • 1. Custom Posts and Meta Boxes
  • 2. About Me Md. Liton Arefin Senior Developer JoomShaper
  • 3. What is Post Type? WordPress can hold and display many different types of content. A single item of such a content is generally called a post, post is also a specific post type.
  • 4. Custom Post Types • Post • Page • Attachment • Revision • Navigation
  • 5.
  • 6. Where Post Type Locates? • Post type stored in “wp_posts” database table
  • 7. When Custom Post Type Needs? • If you need to Develop websites like: • www.youtube.com • www.bbc.co.uk Etc • Most Used Custom Post Type and Meta Fields • Geo Theme (http://www.geotheme.com)
  • 8. When Custom Post Type Needs? When Websites Contains: • Homepage Slider • Callout Boxes • Portfolio • Gallery (Image, Video etc) • Team/People/Staff • Job Posting • Products • Pricing Table • etc
  • 11. What we need to create a Portfolio?
  • 12. What we need to create a Portfolio? • Title • Custom Field (Website Address) • Content • Thumbnail Image • Taxonomy Category/Tags
  • 13. Register Custom Post Type  register_post_type is called when you need to create or modify a post_type. register_post_type should only be invoked through the ‘init’ action. Reference http://codex.wordpress.org/Function_Reference/register_post_type Reserved Post Types • post • page • attactment • revision • nav_menu_item <?php register_post_type( $post_type, $args ) ?>
  • 14. Practical Example function sp_portfolio() { $labels = array( 'name' => _x( 'Portfolio', 'post type general name' ), 'singular_name' => _x( 'Portfolio', 'post type singular name' ), 'add_new' => _x( 'Add New', 'book' ), 'add_new_item' => __( 'Add New Portfolio' ), 'edit_item' => __( 'Edit Portfolio' ), 'new_item' => __( 'New Portfolio Items' ), 'all_items' => __( 'All Portfolio' ), 'view_item' => __( 'View Portfolio' ), 'search_items' => __( 'Search Portfolio' ), 'not_found' => __( 'No Portfolio Items found' ), 'not_found_in_trash' => __( 'No Portfolio Items found in the Trash' ), 'parent_item_colon' => '', 'menu_name' => 'SP Portfolio' ); );
  • 15. $args = array( 'labels' => $labels, 'description' => 'Holds Portfolio specific data', 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'portfolio/%year%', 'with_front' => true), 'capability_type'=> 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 5, 'supports' => array( 'title', 'editor', 'thumbnail'), 'menu_icon' => plugins_url( 'images/icon1.png', __FILE__ ) // Icon Path ); register_post_type( 'portfolio', $args );
  • 17. Register Taxonomy Reference: http://codex.wordpress.org/Function_Reference/register_taxonomy <?php register_taxonomy( $taxonomy, $object_type, $args ); ?> // Custom Portfolio Categories $labels = array('name' => _x( 'Categories', 'taxonomy general name' ), 'singular_name' => _x( 'SP Category', 'taxonomy singular name' ), 'search_items' => __( 'Search Types' ), 'all_items' => __( 'All Categories' ), 'parent_item' => __( 'Parent Category' ), 'parent_item_colon' => __( 'Parent Category:' ), 'edit_item' => __( 'Edit Category' ), 'update_item' => __( 'Update Category' ), 'add_new_item' => __( 'Add New Category' ), 'new_item_name' => __( 'New Category Name' ), ); // Custom taxonomy for Project Tags register_taxonomy('sptag', array('portfolio'), array( 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'query_var' => true, 'rewrite' =>true, )); } add_action( 'init', 'sp_portfolio' );
  • 18.
  • 19. Meta Box field for Custom Post Type Reference: http://codex.wordpress.org/Function_Reference/add_meta_box <?php   add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args ); ?> add_action('admin_init','sp_portfolio_meta'); function sp_portfolio_meta() { // add a meta box for WordPress 'project' type add_meta_box('sp_portfolio', 'Portfolio URL', 'sp_portfolio_meta_setup', 'portfolio', 'side', 'low');          // add a callback function to save any data a user enters in add_action('save_post','sp_portfolio_meta_save');   } function sp_portfolio_meta_setup() { global $post; ?> <div class="portfolio_meta_control"> <p> <input type="text" name="_url" value="<?php echo get_post_meta($post->ID,'_url',TRUE); ?>" style="width: 100%;" /> </p> </div> <?php // create for validation echo '<input type="hidden" name="sp_meta_nonce" value="' . wp_create_nonce(__FILE__) . '" />'; }
  • 20. function sp_portfolio_meta_save($post_id) { // check nonce if (!isset($_POST['sp_meta_nonce']) || !wp_verify_nonce($_POST['sp_meta_nonce'], __FILE__)) { return $post_id; } // check capabilities if (portfolio' == $_POST[post_type']) { if (!current_user_can('edit_post', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_page', $post_id)) { return $post_id; } // exit on autosave if (defined('DOING_AUTOSAVE') == DOING_AUTOSAVE) { return $post_id; } if(isset($_POST['_url'])) { update_post_meta($post_id, '_url', $_POST['_url']); } else { delete_post_meta($post_id, '_url'); } About Nonces: http://codex.wordpress.org/Function_Reference/wp_create_nonce
  • 21.
  • 23. function sp_add_columns($cols) { $cols['title'] = __('Portfolio Title'); $cols['thumbnail'] = __('Thumbnail'); $cols['description'] =__('Description'); $cols['_url'] =__('Portfolio URL'); $cols['sptag'] = __('Categories'); //Unset Default Date, Author etc unset  ($cols['date'], $cols['author']); return $cols; } function sp_add_column_values($column_name, $post_id) { $width = (int) 100; $height = (int) 100; if ( 'thumbnail' == $column_name ) { $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true ); // image from gallery $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'portfolio', 'post_mime_type' => 'image') ); if ($thumbnail_id) $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true ); elseif ($attachments) { foreach ( $attachments as $attachment_id => $attachment ) { $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true ); } } if ( isset($thumb) && $thumb ) { echo $thumb; } else { echo __('None'); }}
  • 24. elseif ('description' == $column_name) { echo the_content(); } elseif ('_url' == $column_name) { echo get_post_meta($post_id, '_url', true); } elseif ('sptag' == $column_name) { $terms = wp_get_post_terms(get_the_ID(), 'sptag' ); $t = array(); foreach($terms as $term) $t[] = $term->slug; echo implode(', ', $t); $t = array(); } } // For Portfolio Items add_filter( 'manage_portfolio_posts_columns', 'sp_add_columns' ); add_action( 'manage_portfolio_posts_custom_column', 'sp_add_column_values', 10, 2 ); Reference: http://codex.wordpress.org/Plugin_API/Filter_Reference/manage_$post_type_posts_columns http://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column http://codex.wordpress.org/Plugin_API/Filter_Reference/manage_edit-post_type_columns http://justintadlock.com/archives/2011/06/27/custom-columns-for-custom-post-types
  • 25. How to show Contents? There are few options to retrieve custom posts query_posts() WP_Query() get_posts() Refefences: http://codex.wordpress.org/Function_Reference/query_posts http://codex.wordpress.org/Class_Reference/WP_Query http://codex.wordpress.org/Template_Tags/get_posts
  • 26. Query_posts() <?php /* * Template Name: SP Portfolio */ get_header(); query_posts(array('post_type' => 'portfolio', 'posts_per_page' => -1)); ?> <div class=“container”> <?php if(have_posts()){ while(have_posts()){ the_post(); ?> <article class=“post-<?php the_ID(); ?>" <?php post_class(); ?>> <h2><?php the_title();?></h2> <p><?php the_content();?></p> <a href=“<?php echo get_post_meta($post->ID, '_url', true); ?>”></a> </article> <?php } } // Reset Query wp_reset_query(); ?> </div> <?php get_footer();?>
  • 27. WP_Query() <?php /* * Template Name: SP Portfolio */ get_header(); $args = array('post_type' => 'portfolio', 'posts_per_page' => -1); $query = new WP_Query( $args ); ?> <div class=“container”> <?php if($query->have_posts()){ while($query->have_posts()){$query->the_post(); ?> <article class=“post-<?php the_ID(); ?>" <?php post_class(); ?>> <h2><?php echo get_the_title();?></h2> <p><?php echo get_the_content();?></p> <a href=“<?php echo get_post_meta($post->ID, '_url', true); ?>”></a> </article> <?php } } // Restore original Post Data wp_reset_postdata(); ?> </div> <?php get_footer();?>
  • 28. get_posts() <?php /* * Template Name: SP Portfolio */ get_header(); $args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 1 ); $query = get_posts( $args ); foreach ( $query as $post ) { setup_postdata( $post ); ?> <div class=“container”> <article class=“post-<?php the_ID(); ?>" <?php post_class(); ?>> <h2> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </h2> <p><?php the_content();?></p> <a href=“<?php echo get_post_meta($post->ID, '_url', true); ?>”></a> </article> <?php } // Restore original Post Data wp_reset_postdata(); ?> </div> <?php get_footer();?>
  • 29. Which one is best? query_posts() : alter of main query. Post-related global variables and template tags will be altered.  WP_Query() : defined in wp-includes/query.php. wp-blog-header.php gives $wp_query object information. $is_* holds the informations. get_posts() : returns array of posts. Direct access to database using WP_Query() get_posts() is best to use.
  • 30. Page Template function sp_template_redirect($template_path ) { if ('portfolio' == $_POST['post_type']) { $template_path = plugin_dir_path( __FILE__ ) . '/theme/page-portfolio.php'; } return $template_path; } add_action(‘template_redirect’,’ sp_template_redirect’);
  • 31. You should use For secondary query like sidebar widget posts use WP_Query or get_posts()
  • 32. References • http://generatewp.com/ • http://www.joomshaper.com/blog/wordpress/create-a-custom-post-type-in-wordpress • http://www.joomshaper.com/blog/wordpress/add-meta-boxes-in-custom-post-type • http://wp.smashingmagazine.com/2012/11/08/complete-guide-custom-post-types/ • http://wp.tutsplus.com/tutorials/plugins/a-guide-to-wordpress-custom-post-types-creation- display-and-meta-boxes/ • http://wp.tutsplus.com/tutorials/creative-coding/custom-page-template-page-based-on-url- rewrite/ • http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-the-basics/ • http://wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-post-types-taxonomies/