WordPress Custom Post Type Dynamic Sub Pages

The Problem

You can’t separate a Custom Post Type into multiple pages. e.g. a project home page, and a project details sub page, and a project activity sub page, etc.

Related Links:

A Solution

Utilize add_rewrite_tag and add_rewrite rule inside functions.php. This will allow you to have URLs like:
  • /project/project-title (default WordPress URL)
  • /project/project-title/details (custom “details” sub page of the “project” custom post type )
  • /project/project-title/activity (custom “activity” sub page of the “project” custom post type )
function custom_post_type_sub_page_urls(){
  add_rewrite_tag('%custom_post_type_sub_page%', '([^&]+)');
  add_rewrite_rule(
    'project/([^/]*)/([^/]*)',
    'index.php?project=$matches[1]&custom_post_type_sub_page=$matches[2]',
    'top'
  );
  flush_rewrite_rules();
}
add_action('init', 'custom_post_type_sub_page_urls');

Then in you Custom Post Type single template single-project.php

switch ($wp_query->query_vars['custom_post_type_sub_page']) {
case 'details':
  // render single-project-details.php
  break;
case 'activity':
  // render single-project-activity.php
  break;
}

I utilized this to show different groups of custom fields per page.  I’m using the %postname% permalink format.

This entry was posted in code. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Marco Almeida
    Posted July 6, 2013 at 4:59 pm | Permalink

    Awesome. This stuff saved my life on a project.

    I’m now trying to get a 3rd level but It’s not working. Can you help
    I’m trying to have a sub-sub-page of a specific sub-page called “speakers”:

    function custom_post_type_sub_page_urls(){
      add_rewrite_tag('%custom_post_type_sub_page%', '([^&]+)');
      add_rewrite_rule(
        'event/([^/]*)/([^/]*)',
        'index.php?event=$matches[1]&custom_post_type_sub_page=$matches[2]',
        'top'
      );
      add_rewrite_tag('%custom_post_speaker%', '([^&]+)');
      add_rewrite_rule(
        'event/([^/]*)/speakers/([^/]*)',
        'index.php?event=$matches[1]&custom_post_type_sub_page=speakers&custom_post_speaker=$matches[2]',
        'top'
      );
      flush_rewrite_rules();
    }
    add_action('init', 'custom_post_type_sub_page_urls');
    

    Any idea why it’s not working?

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>