megclaypool of Rootid
8/16/2018 - 3:50 PM

Custom Post Types and Taxonomies in WordPress

How to create custom post types and taxonomies in WordPress

This stuff needs to go in one of the php files. For Protect the Protest, Jason created a register_custom_types.php file.

I'm just going to put the contents of that file here, so I can copy and adapt it later as need be:

<?php

// Register custom post types and taxonomies here.

function radicati_theme_init() {
  if(!taxonomy_exists('promotion_options')) {
    register_taxonomy('promotion_options', ['resource', 'post'], [
      'label' => __('Promotion Options'),
      'hierarchical' => true,
      'rewrite' => false,
      'public' => false,
      'show_ui' => true,
    ]);
  }

  if(!post_type_exists('resource')) {
    register_post_type('resource', [
      'label' => 'Resources',
      'labels' => [
        'name' => 'Resources',
        'singluar_name' => 'Resource',
      ],
      'public' => true,
      'show_in_menu' => true,
      'menu_position' => 5,
      'menu_icon' => 'dashicons-admin-tools',
      'supports' => [
        'title', 'editor', 'excerpt', 'page-attributes', 'thumbnail', 'custom-fields', 'author'
      ],
      'capability_type' => 'post',
      'taxonomies' => ['category', 'post_tag'],
    ]);
  }

  if(!term_exists('promoted_to_front_page', 'promotion_options')) {
    wp_insert_term('Promoted to Front Page', 'promotion_options', [
      'description' => 'Content that should displayed on the front page',
      'slug' => 'promoted_to_front_page',
    ]);

    // Add other default promotion options here.
  }

}

add_action('init', 'radicati_theme_init');


// Add Resources to category archive pages

function radicati__pre_get_posts($query) {
  if( (is_category() || is_tag()) && $query->is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
    $query->set( 'post_type', array(
      'post', 'resource'
    ));
  }
  return $query;
}
add_filter('pre_get_posts', 'radicati__pre_get_posts');