WordPress custom post type endpoint

Requirement:

If you want to add endpoint, let say “books” to  CPT author, and wants to change view in template.

Solutions:

No need to use “add_rewrite_endpoint” function because as of today, we can not add endpoint to CPT only ( we can add endpoints to either page or archives or all links, etc using  add_rewrite_endpoint function )

So how to do it ? Simple, only two functions and use if condition in template file to show list of books or whatever…

<?php
function myplugin_register_query_vars( $vars ) {
 $vars[] = 'books';
 return $vars;
}
add_filter( 'query_vars', 'myplugin_register_query_vars' );


function myplugin_rewrite_rule() {
 add_rewrite_rule( 'author/([^/]+)/books/?', 'index.php?post_type=author&name=$matches[1]&books=true','top' );
}
add_action('init', 'myplugin_rewrite_rule', 10, 0); ?>

In template just check if condition as follow:

if( get_query_var('evaluate') ){
 // modify view here
} else {
 // default code could be the_content();
}

Leave a Reply

Your email address will not be published. Required fields are marked *