Custom routes for custom post type?

I have a custom post type called 'event'. An event has multiple subpages like registration, speakers, contact us, etc. Currently the content is saved as one or more custom fields.

I would like to have an url structure like

  • events/{event_slug}/registration
  • events/{event_slug}/speakers
  • events/{event_slug}/contactus

With each URL displaying the information from each custom field, respectively.

Is there a way, we can achieve this in WordPress?

Topic routing wp-remote-request custom-post-types Wordpress

Category Web


One way is to enter an additional query variable and rewrite rule to set it. Meta fields will be displayed based on this new query variable.

add_filter( 'query_vars', 'se353995_query_vars' );
add_action( 'init', 'se353995_sublinks', 20 );

function se353995_query_vars( $vars )
{
    $vars[] = "subpage";
    return $vars;
}
function se353995_sublinks()
{
    $cpt_slug = 'events';
    $sublinks = '(registration|speakers|contactus)';

    add_rewrite_rule(
        "$cpt_slug/([^/]+)(?:/$sublinks)/?$",
        'index.php?'.$cpt_slug.'=$matches[1]&post_type='.$cpt_slug.'&subpage=$matches[2]',
        'top'
    );
}

An example of how to display the page, single-events.php:

while ( have_posts() ) :
    the_post();

    // check what event subpage to display
    $qv = get_query_var( 'subpage', false );
    if ( $qv == 'registration' )
    {
        // display "registration" subpage
        //
        $customfield_reg = get_post_meta(get_the_ID(), 'meta_field_name', true) );
    }
    else if ( $qv == 'speakers' )
    {
        // display "child page" 
        //
        $customfield_reg = get_post_meta(get_the_ID(), 'other_field_name', true) ;
    }
    else
    {
        // default one
        //
        get_template_part( 'content', 'single' );
    }

endwhile; // End of the loop.

You may want to use this resource. You can create own post types links (and probably relational template structure)

They said you can create domain.com/{prefix}/{post-type-slug}/{postname} like URLs with their code (Also you create even custom ones).

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.