WP Smith

Creating WordPress & Genesis Websites Since 2010

  • Home
  • About
  • Services
  • Blog
  • Contact

Jun 08 2011

Displaying Custom Post Types

Understanding WordPress Custom Post Types

There are several ways to display your custom post types:

  1. Display Custom Post Types with Blog Posts
  2. Display Custom Post Types with Custom Loop
  3. Display Custom Post Types via Shortcode

Display Custom Post Types with Posts

To display them with posts on the blog page, you can add this bit of code to your functions.php file:

[php]
add_filter( 'pre_get_posts' , 'wps_add_my_cpt' );
function wps_add_my_cpt() {
if ( is_home() && false == $query->query_vars['suppress_filters'] ) //if you want it to appear in the feed, comment this line & use the next line
if ( ( is_home() && false == $query->query_vars['suppress_filters'] ) || is_feed() )
$query->set( 'post_type' , 'array( 'post' , 'wps_cars' );
return $query;
}[/php]

Display Custom Post Types with Custom Loop

WordPress added support for single-type-template in Version 3.0 and for archive-type-template in Version 3.1.

Single template

In the form of the single-type-template. In the same way that posts are shown on their own page with single.php, custom post types will use single-{posttype}.php if it's available.

So for the above example, you could create a single-wps_cars.php file and the product posts would be shown using that template.

Archive template

In the form of the archive-type-template. In the same way that posts are shown on their own archive with archive.php, custom post types will use archive-{posttype}.php if it's available.

So for the above example, you could create a archive-wps_cars.php file and the product posts would be shown using that template.

*Note: Use the is_post_type_archive() function to check if the query shows post type archive page, and the post_type_archive_title() to echo the post type title.

Custom Post Type Custom Loops

To create your own custom loop in your page template (or, for Genesis users, you can see my post, <a href="https://wpsmith.net/frameworks/how-to-create-a-wordpress-custom-post-type-template-in-genesis/" target="_blank">How to Create a WordPress Custom Post Type Template in Genesis</a>), you can add this bit of code:

[php]$args = array( 'post_type' => 'wps_cars' , 'posts_per_page' => 5 , 'orderby' => 'post_title' , 'order' => 'ASC' );
$carsloop = new WP_Query( $args );
if ( $carsloop->have_posts() ) {
$output = '<div id="cars-content">';
while ( $carsloop ->have_posts() ) : $carsloop ->the_post();
$output .= the_title();
$output .= '<div class="entry-content">';
$output .= the_content();
$output .= '</div>';
endwhile;
$output .= '</div>';
}
else
$output = '<p>No cars were found.</p>';
[/php]

Display Custom Post Types via Shortcode

One way to display custom post types is to create a shortcode (thanks to Mark Jaquith, @markjaquith) to display them on pages or posts. There are a variety of reasons to use them and a variety of reasons that these can be abused. However, the benefits outweigh the risks and if done well, this can improve the user experience.

To display the cars custom post type that we have been working with, simply create a page and insert [ cars] (without the space in the front) to display wps_cars posts as a posts page (except we are ordering by Post Title in ascending order).

[php]function wps_cars_posting() {
global $post;
$xglobals = $GLOBALS;
$args = array( 'post_type' => 'wps_cars' , 'posts_per_page' => 5 , 'orderby' => 'post_title' , 'order' => 'ASC' );
$carsloop = new WP_Query( $args );
$output = '';
if ( $carsloop->have_posts() ) {
while ( $carsloop->have_posts() ): $carsloop->the_post();
$output .= '<div id="cars-content">';
$output .= get_the_post_thumbnail( $post->ID, 'thumbnail' );
$output .= '<strong>';
$output .= get_the_title();
$output .= '</strong>';
if (!empty( $post->post_excerpt ) )
$output .= '<em>'.$post->post_excerpt.'</em>';
$output .= get_the_content();
$output .= '</div>';
endwhile;
}
else
$output = '<p>No cars were found.</p>';
$GLOBALS = $xglobals;
return $output;
}

function my_init() {
add_shortcode( 'cars' , 'wps_cars_posting' );
}

add_action('init' , 'my_init');
[/php]

Be sure to add CSS your style.css accordingly.

For Genesis users, you can use the custom_loop function.

Written by Travis Smith · Categorized: Custom Post Types

Jun 07 2011

Custom Post Types and Using Meta Boxes

Understanding WordPress Custom Post Types

First, if there is any confusion, WordPress refers to metaboxes as one word (see add_meta_box and remove_meta_box). The confusion rises because of the function name which separates the words. While I am not going to speculate as to the right way, as far as I am concerned, it doesn't matter. But that may be because I don't have a dog in the fight or discussion. So I will defer to better and smarter people. These same zealots are the ones who argue for the proper spelling of WordPress not extending grace at times, even when a person who knows better may mistakenly type something different. Again, to me, while spelling WordPress correctly matters from a branding perspective, from a developer's perspective where everything is lower case or camel case, again it doesn't matter (esp since all WordPress functions abbreviate WordPress to wp_). Now on to more pressing things (function off_soap_box() {break;}).

There are several posts on how to incorporate custom fields and metaboxes into your custom post type. To me this is the most difficult part of custom post types. You can also find a plethora of examples and tutorials of custom metaboxes for your custom post type that use simple text fields or text areas (e.g., a good video metabox example by Andrew Dodson, a good example here by function, new2wp for a simple metabox for links & link descriptions, Re-cycled Air, .net Magazine for Tumblr-like metabox for quotes with post formats), as those are the most popular. However, finding good tutorials on the use of checkboxes or radio buttons are a bit more difficult to find. Jeremiah Tolbert gives a good tutorial on a dropdown selection metabox.

Two notable examples are Curtis Henson's Links custom post type using a PHP Class and WPTheming's Events metaboxes, good thorough tutorial.

However, I need to clarify something that I hear a lot. When you register your custom post type, you have the opportunity to use an argument called "register_meta_box_cb." However, you do not have to use that argument. Using it allows you to cut a couple steps, but if you are using free custom post type plugins then they probably do not offer this ability.

To add a metabox to a custom post type,
[php]<?php
// Add the Metabox for CPT

add_action( 'add_meta_boxes', 'add_cpt_metabox', 10 ); //note, it has to be add_meta_boxes hook for WP 3.0+
function add_cpt_metabox() {
add_meta_box('cpt-metabox', 'Metabox TITLE', 'prefix_cpt_metabox_function', 'my_cpt_registered_name', 'normal', 'default');
}

// The CPT Metabox
function prefix_cpt_metabox_function() {
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="cpt_metabox_noncename" id="cpt_metabox_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

// Echo metabox body stuff (fields/text, etc)
}

/* Do something with the data entered */
add_action( 'save_post', 'prefix_cpt_metabox_save_postdata' );
function prefix_cpt_metabox_save_postdata( $post_id ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;

// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times

if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
return;

// Check permissions
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}

// OK, we're authenticated: we need to find and save the data

$mydata = $_POST['myplugin_new_field'];

// Do something with $mydata
// probably using add_post_meta(), update_post_meta(), or
// a custom table (see Further Reading section below)

return $mydata;
}
[/php]

For a good alternative for saving, see Nathan Rice's code: Adapted version presented by WP Theming's Post, How to Add a Metabox to a Custom Post Type.

These examples provide good hard coding examples, so I wanted to discuss two other possibilities.
First is a plugin: More Fields, which works perfectly with More Types and More Taxonomies.

Custom Post Types and Custom Metaboxes
Click for Larger Image

Second and a much better choice in my option as it is extremely flexible is the Custom Metaboxes and Fields for WordPress script by Andrew Norcross (@norcross), Jared Atchison (@jaredatch), and Bill Erickson (@billerickson). Bill Erickson has written a brief example here with an excellent subsequent discussion in the comments area.

However, here is an example that I have used recently with a restaurant theme and a menu item post type.

Here’s how to set up your own metaboxes:

  1. Download a copy of our metabox code from GitHub
  2. Create a “lib” directory in your theme or child theme, and a “metabox” directory inside “lib”. Upload the files you downloaded above into /wp-content/themes/your-theme/lib/metabox
  3. Include '/lib/metabox/init.php' in your functions.php file, and define your metaboxes in an array (see below). For Genesis users, it's require_once( CHILD_DIR . '/lib/metabox/init.php' );; for others, try require_once( STYLESHEETPATH . '/lib/metabox/init.php' );

Each metabox is stored as an array. There’s a ton of field options, including text, textarea, checkbox, dropdown list, and WYSIWYG. For examples on how to use all the fields, look at /metabox/example-functions.php.

First step is that I registered my custom post type.

[php]<?php add_action('init', 'dp_cpt_init');
function dp_cpt_init() {
$labels= array( 'name' =--> _x('Menu Items', 'post type general name'),
'singular_name' => _x('Menu Item', 'post type singular name'),
'add_new' => _x('Add New', 'menu_item'),
'add_new_item' => __('Add New Menu Item'),
'edit_item' => __('Edit Menu Item'),
'new_item' => __('New Menu Item'),
'view_item' => __('View Menu Item'),
'search_items' => __('Search Menu Item'),
'not_found' => __('No menu items found'),
'not_found_in_trash' => __('No menu items found in Trash'),
'parent_item_colon' => '',
'menu_name' => 'Menu Items'
);

$args = array(
'labels' => $labels,
'description' => 'Menu items for various menus.',
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array('slug' => 'menu-item'),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'menu_icon' => CHILD_URL .'/lib/cpt/images/menu_item_cpt_16x16.png',
'supports' => array('title','editor','revisions','thumbnail'),
'taxonomies' => array('dp_menu','dp_toppings')
);
register_post_type( 'dp_menu_items' , $args );

}

add_action( 'init', 'dp_create_custom_taxonomies', 0 );
function dp_create_custom_taxonomies() {
//Register Taxonomies
register_taxonomy('dp_menu',array (0 => 'dp_menu_items'),array( 'hierarchical' => true, 'label' => 'Menus','show_ui' => true,'query_var' => true,'rewrite' => array('slug' => 'menus'),'singular_label' => 'Menu') );
register_taxonomy('dp_toppings',array (0 => 'dp_menu_items'),array( 'hierarchical' => false, 'label' => 'Toppings','show_ui' => true,'query_var' => true,'rewrite' => array('slug' => 'toppings'),'singular_label' => 'Topping') );
}
[/php]

Second step is to follow Bill's steps, and add the following below the previous content.

[php]require_once( CHILD_DIR . '/lib/metabox/init.php' );
// Include & setup custom metabox and fields
$prefix = 'dp_';
$meta_boxes = array();
global $price_info;

$meta_boxes[] = array(
'id' => 'dp_menu_item_info',
'title' => 'Menu Item Price Information',
'pages' => array('dp_menu_items'), // post type
'context' => 'side',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => 'Small Pizza Price',
'desc' => 'Small Pizza',
'id' => $prefix . 'price_textmoney', // dp_price_textmoney
'type' => 'text_money'
),
array(
'name' => 'Medium Pizza Price',
'desc' => 'Medium Pizza',
'id' => $prefix . 'price1_textmoney', // dp_price1_textmoney
'type' => 'text_money'
),
array(
'name' => 'Large Pizza Price',
'desc' => 'Large Pizza',
'id' => $prefix . 'price2_textmoney', // dp_price2_textmoney
'type' => 'text_money'
),
array(
'name' => 'Extra Large Pizza Price',
'desc' => 'XL Pizza',
'id' => $prefix . 'price3_textmoney', // dp_price3_textmoney
'type' => 'text_money'
),
array(
'name' => 'Sale Price',
'desc' => 'Sale Campaign Price',
'id' => $prefix . 'price4_textmoney', // dp_price4_textmoney
'type' => 'text_money'
)
)
);
[/php]
And here is an example of the outcome:
Custom Post Type metabox Example

Written by Travis Smith · Categorized: Custom Post Types

Jun 06 2011

Custom Post Types and Custom Taxonomies

Understanding WordPress Custom Post Types
To me, custom post types cannot be divorced from custom taxonomies. Two of the criteria that I consider before creating a custom post type is:

  1. Can my goal/objective be accomplished through the use of custom taxonomies?
  2. Do I need to use custom taxonomies?

This being said, WordPress's out of the box compatibility with custom taxonomies is still developing. However, one individual, Michael Fields, is pioneering WordPress's custom taxonomies functionality and capabilities. So I wanted to highlight some of the things he has already created.

Michael has excellent posts on Taxonomy in WordPress. To highlight one in particular, New and Exciting Ways to Organize Your WordPress Powered Website, which is all about how to achieve better organization in WordPress (for a text-only page, see Understanding Taxonomy in WordPress). In this post, he includes this video:

However, Michael has more on Taxonomy in WordPress including some extremely helpful plugins and widgets. Consider these:

Taxonomy Images Plugin

May 31, 2011 – This plugin allows you to associate images from your media library to categories, tags and custom taxonomies. … Download the plugin

Taxonomy List Shortcode Plugin

The Taxonomy List Shortcode plugin adds a shortcode to your WordPress installation which enables you to display multiple unordered lists containing every term of a given taxonomy. After speaking with Michael, Michael informed me that a massive overhaul is coming soon introducing full
theme integration plus special option(s) that integrate with Taxonomy Images. It should be very exciting.  … View this page, Download the plugin

Dealing with Long Taxonomy Descriptions in the WordPress Administration Panels

Probably Michael's most under-rated plugin. This plugin allows you to take full advantage of the taxonomy system the the latest version of WordPress. Unfortunately, the taxonomy administration panels tend to get quickly bloated where terms have descriptions that are longer than a few words. It trims the term description down to a short length when viewing multiple terms in the administration panels. If you have really long taxonomy descriptions then you might only be able to view one or two terms per screen. This plugin fixes that. Here is a quick and easy method to help put an end to long descriptions messing with your work flow. … View the code, Download the plugin

Taxonomy Widget Plugin

The Taxonomy Widget Plugin enables users of all skill levels to create widgets in their sidebar that display all terms of any given post taxonomy including tags and categories. Users can choose between 3 different templates including two types of lists, a term cloud or a dropdown menu. … View this page, Download the plugin

Taxonomy Terms List Plugin

This plugin will create a list for each taxonomy whose terms have been associated to a given post. These list will appear after the post content. This plugin will not effect builtin taxonomies such as categories, tags and link categories. … View this page, Download the plugin

One particular post that deserves some attention (and got Michael's attention) is Otto's post on Custom Taxonomies.

Advanced Taxonomy Queries in WordPress 3.1

Otto does a great job of explaining some of the additions to the taxonomy system in WordPress 3.1. I’ve been using this article as a reference for the past few days. ... View this Bookmark

Other posts by Michael include:

Set Default Terms for your Custom Taxonomies

Sep 14, 2010 – If you’ve ever created a post in WordPress, you’ll know that you have to put it in a category. There’s no way around this, if you try to fight it, you will lose! On the other hand, there is really no way to define a default for custom taxonomies. I created the following code to … View this post

Append a posts taxonomy terms to post class.

Jul 11, 2010 – The following code snippet will enable your theme to append the slug of every term of a given taxonomy that has been associated to the current post. You will most likely want to change the value of the $taxonomy variable to match a taxonomy registered for the post type you are targeting. View this post

Dynamically Create Actions for Every Defined Taxonomy’s Column Header

Jun 4, 2010 – Taxonomy support in WordPress 3.0 has improved in many places. During the time I spent updating a few of my plugins, I noticed that dynamic filters had been defined for the columns that appear on edit-tags.php – the file that lists the terms for each taxonomy in the administration panels. The following snippet demonstrates how … View this post

Remove Taxonomy Box from WordPress Administration Panels

While Michael only posted this for his own reference, it's good stuff nonetheless. I’m posting this here pretty much for my own reference. The idea is to create an array of taxonomy slugs that you want to hide from the Edit screens in The WordPress Administration Panels. You can then loop over the global $wp_taxonomies variable and if the taxonomy is present in the $hide array, the WordPress … View this post

Besides these excellent posts, Michael has a plethora of taxonomy plugins that are extremely useful. There was one particular instance that I needed something like wp_dropdown_categories() regarding custom taxonomies and Michael submitted a trac ticket in WordPress and via PasteBin. So Michael created a forked version of wp_dropdown_categories() calling it mfields_dropdown_taxonomy_terms(). Michael has since moved and revised the code in the Taxonomy Widget. The much simplified version which uses only a custom walker in the code of the taxonomy widget plugin (code starts on line 365 ... The custom walker is used on line 300 - args start on line 288).

Written by Travis Smith · Categorized: Custom Post Types

Jun 06 2011

How to Create a Genesis Page Template with a Custom Post Type with Custom Content in Custom Fields

Recently, someone asked me how I would create a Genesis Page Template with a Custom Post Type using Custom Fields. One of the great things about Genesis is its ability to easily pull custom fields content. Previously I mentioned how to create a WordPress Custom Post Type Page Template in Genesis. Now, what if I want to have this page template to display custom content via custom fields?

Well here's the right way to do it via Genesis hooks:
[php]
<?php
/*
*Template Name: Author Interview
*/

remove_action('genesis_loop', 'genesis_do_loop');
add_action('genesis_loop', 'custom_do_loop');
function custom_do_loop() {
$mycpt = 'books';
$posts_per_page = 10;
global $paged;
$args = array('post_type' => $mycpt, 'posts_per_page' => $posts_per_page);

genesis_custom_loop( $args );
}

remove_action( 'genesis_post_content' , 'genesis_do_post_content' );
add_action( 'genesis_post_content' , 'genesis_do_custom_post_content' );

function genesis_do_custom_post_content() { ?>
<div id="post-<?php the_ID(); ?>" class="book-info">
<h3>Book Information</h3>
<p class="book-description"><strong>Description</strong>: <?php echo genesis_get_custom_field('_type'); ?></p>
<p class="book-pages"><strong><?php echo genesis_get_custom_field('_type'); ?></strong>: <?php echo genesis_get_custom_field('_pages'); ?> pages </p>
<p class="book-publisher"><strong>Publisher</strong>: <?php echo genesis_get_custom_field('_publisher'); ?> (<?php echo genesis_get_custom_field('_pub_date'); ?>)</p>
</div><!--end .book-info -->
<div id="post-<?php the_ID(); ?>" class="book-review">
<?php the_content(); //OR, the_excerpt(); OR, the_content_limit( (int)genesis_get_option('content_archive_limit'), __('[Read more...]', 'genesis') ); ?>
</div><!--end .book-review -->
<?php
}

genesis();
?>
[/php]

Written by Travis Smith · Categorized: WordPress

Jun 03 2011

Genesis Specific: Add Genesis SEO and Layout Options to My Custom Post Type

Understanding WordPress Custom Post Types
So if you are running on the Genesis Framework, and you've created your new custom post type. So where are the SEO options!? Well, more than likely, you didn't add support for the Genesis SEO options to your custom post types. This feature alone makes Genesis so powerful and such an awesome Theme Framework. To add the Genesis SEO options only takes one additional support code, not even one line.

Wherever you registered your custom post type, add 'genesis-seo', 'genesis-layouts' to the support array. And there it is! Genesis SEO options are now available for your custom post type! (see sample example below).

If you do not have the registration code or the plugin does not allow you to add custom support features, no problem! Just use, add_post_type_support();. In your functions.php, add the following:
[php]
add_post_type_support( 'wps_cars', 'genesis-seo' );
add_post_type_support( 'wps_cars', 'genesis-layouts' );
[/php]

It would need to occur in the 'init' hook. So, in your functions.php, it will appear as:
[php]add_action('init', 'my_custom_init');

function my_custom_init() {
add_post_type_support( 'wps_cars', 'genesis-seo' );
add_post_type_support( 'wps_cars', 'genesis-layouts' );
}

[/php]

Sample Custom Post Type Registration with Genesis SEO Support

[php highlight="26"]add_action('init', 'wps_cpt_init');
function wps_cpt_init() {
$labels= array(
'name' => _x('Cars', 'post type general name'),
'singular_name' => _x('Car', 'post type singular name'),
'add_new' => _x('Add New', 'car'),
'add_new_item' => __('Add New Car'),
'edit_item' => __('Edit Car'),
'new_item' => __('New Car'),
'view_item' => __('View Car'),
'search_items' => __('Search Car'),
'not_found' => __('No cars found'),
'not_found_in_trash' => __('No cars found in Trash'),
'parent_item_colon' => '',
'menu_name' => 'Cars'
);
$args = array(
'labels' => $labels,
'public' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','author','thumbnail','genesis-seo')
);
register_post_type( 'wps_cars' , $args );
}[/php]

Written by Travis Smith · Categorized: Custom Post Types, Genesis

  • « Previous Page
  • 1
  • …
  • 37
  • 38
  • 39
  • 40
  • 41
  • …
  • 60
  • Next Page »

Need Help?

Please let us know how we can help you!

Get Help

Recommendations

Genesis WordPress Framework
Sucuri Security
Gravity Forms
GetSoliloquy
Get Envira
Scribe SEO
BackupBuddy
WordPress Video User Manuals

Recent Posts

  • Solving WordPress 5XX Server Errors on SiteGround
  • Hiding an User in the WordPress Admin
  • Custom Rewrite Rules for Custom Post Types and Taxonomies
  • WordPress JavaScript Manager Native Functions
  • Causes of WordPress Site Performance Slowdown

About Travis

As a WordPress enthusiast, developer, and speaker, Travis writes about what he learns in WordPress trying to help other WordPress travelers, beginners and enthusiasts with tutorials, explanations, & demonstrations.

  • Twitter
  • Facebook
  • LinkedIn
  • Google+
  • RSS

Copyright © 2025 ďż˝ WP Smith on Genesis on Genesis Framework ďż˝ WordPress ďż˝ Log in