Categories
Uncategorized

Day 6: Custom Post Types

Let’s say that you want to create a page on an e-commerce site which shows a product in detail. It is possible to create such a page in wordpress, using custom post types.

WordPress comes with five default post types: post, page, attachment, revision, and menu.

Example to register new post type, Products, which will be defined in database as ‘wporg_product’:

function wporg_custom_post_type() {
    register_post_type('wporg_product',
        array(
            'labels'      => array(
                'name'          => __('Products', 'textdomain'),
                'singular_name' => __('Product', 'textdomain'),
            ),
                'public'      => true,
                'has_archive' => true,
        )
    );
}
add_action('init', 'wporg_custom_post_type');

A custom post type gets its own slug within the site URL structure.

A post of type wporg_product will use the following URL structure by default: http://example.com/wporg_product/%product_name%.

Custom templates for post types

You can create custom templates for your custom post types. In the same way posts and their archives can be displayed using single.php and archive.php, you can create the templates:

  • single-{post_type}.php – for single posts of a custom post type
  • archive-{post_type}.php – for the archive

Query by Post Type

<?php
$args = array(
    'post_type'      => 'product',
    'posts_per_page' => 10,
);
$loop = new WP_Query($args);
while ( $loop->have_posts() ) {
    $loop->the_post();
    ?>
    <div class="entry-content">
        <?php the_title(); ?>
        <?php the_content(); ?>
    </div>
    <?php
}

Altering the main query

function wporg_add_custom_post_types($query) {
    if ( is_home() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'page', 'movie' ) );
    }
    return $query;
}
add_action('pre_get_posts', 'wporg_add_custom_post_types');

Above query shows posts of type ‘post’, ‘page’ and ‘movie’ on the home page of website.

Leave a comment

Design a site like this with WordPress.com
Get started