Custom code for displaying custom post types in WordPress

Alice B Dec 16, 2024 Custom Post Types
How can I show different types of content on my website?
What PHP code can I use to query and display custom post types in WordPress templates?
Andy answered Dec 16, 2024

To display custom post types in WordPress, you can use either a custom code solution or specialized plugins. Here's how to implement both approaches:

Custom Code Solution

This code queries and displays custom post types. Add it to your theme's template files (e.g., page-template.php, archive.php, or index.php):

Basic query to display custom post types:

$args = array(
    'post_type' => 'your_custom_post_type',
    'posts_per_page' => 10,
    'orderby' => 'date',
    'order' => 'DESC'
);

$query = new WP_Query($args);

if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
        ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <div class="entry-content">
                <?php the_excerpt(); ?>
            </div>
        </article>
        <?php
    endwhile;
    wp_reset_postdata();
else :
    echo 'No posts found';
endif;

Advanced query with multiple post types and custom taxonomies:

$args = array(
    'post_type' => array('post_type_1', 'post_type_2'),
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'your_taxonomy',
            'field' => 'slug',
            'terms' => 'your-term'
        )
    ),
    'meta_query' => array(
        array(
            'key' => 'your_custom_field',
            'value' => 'desired_value',
            'compare' => '='
        )
    )
);

$query = new WP_Query($args);

if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
        ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <h2><?php the_title(); ?></h2>
            <?php if (has_post_thumbnail()) : ?>
                <div class="post-thumbnail">
                    <?php the_post_thumbnail('medium'); ?>
                </div>
            <?php endif; ?>
            <div class="entry-content">
                <?php the_content(); ?>
            </div>
        </article>
        <?php
    endwhile;
    wp_reset_postdata();
endif;

Recommended Plugins

  1. Pods - Create and manage custom post types with an intuitive interface
  2. Custom Post Type UI - User-friendly interface for creating custom post types
  3. Toolset Types - Professional solution for custom post types and custom fields

These plugins provide GUI interfaces for managing custom post types and their display options, which might be preferable if you're not comfortable with coding.

The custom code solution offers more flexibility and better performance, while plugins provide easier management and require no coding knowledge.