8 \ December 2018 \ http://www.phparch.com
Custom Post Types in WordPress
For example, if you want to add a field for a URL, you could
template your custom post type page to wrap a featured image
with a link using that URL field. Another example would be
to add a date field so you could display a calendar of events in
chronological order and track start and end dates.
Learn more about ACF^9 on their site.
Displaying Custom Post Type Data
Creating WordPress Templates for Custom Post Types
When creating or working with themes, it is essential to
understand the template hierarchy. You can see a visual map
of this hierarchy in the WordPress documentation^10.
If your CPT is set 'public' => true, your content will
display on one of your default WordPress template pages such
as index.php or single.php.
9 ACF: https://www.advancedcustomfields.com
10 WordPress documentation: https://phpa.me/wordpress-template-hierarchy
If you would like your custom post type layout to look the
same as your other pages, this might be fine. This shows the
power of WordPress. You created something brand new, and
WordPress just makes it work.
But odds are you will want to give your custom post type
pages, archive, and/or listing pages a unique look. Back to our
example of a board of directors listing, we would likely want
to display these members in a grid in alphabetical order, not
in order of most recently added.
You can create custom templates unique to our custom post
types and override these defaults with the following naming
conventions:
- single-{post_type}.php
- archive-{post_type}.php
Listing 6
- <?php
- /*
- **Template Name: Trails Template
- */
- ?>
- <?php get_header(); ?>
- <?php
- if ( have_posts() ) :
- while ( have_posts() ): the_post();
- // Display page content as intro ?>
- <?php the_content(); ?>
- <?php endwhile; endif; ?>
- <? wp_reset_postdata(); ?>
- <?php
- // Second query to display hiking and biking trails
- $args = array(
- 'post_type' => array(
- 'wiverb_hike',
- 'wiverb_bike'
- ),
- 'posts_per_page' => '6',
- 'orderby' => 'title',
- 'order' => 'asc'
- );
- $query2 = new WP_Query( $args );
- if ( $query2->have_posts() ) { ?>
- <?php while ( $query2->have_posts() ) {
- $query2->the_post();
- $postType = get_post_type(get_the_ID());
- switch($postType){
- case 'wiverb_hike':
- $postTypeText = 'Hike';
- $postTypeClass = 'bg-blue';
- break;
- case 'wiverb_bike':
- $postTypeText = 'Bike';
- $postTypeClass = 'bg-red';
- break;
- } ?>
- <?= $postTypeText; ?>
- <?php } //End While
- wp_reset_postdata(); ?>
- <?php } //End if ?>
- <?php get_footer(); ?>