I have created a custom endpoint for Download page with Permalink setting:
/%category%/%postname%/
The URL as below:
domain.com/top-category/child-category/post-slug/download
function themes_download() {
add_rewrite_endpoint( 'download', EP_PERMALINK | EP_PAGES );
}
add_action( 'init', 'themes_download' );
function themes_download_template() {
global $wp_query;
$dl_val = intval( get_query_var( 'download' ) );
// if this is not a request for play or a singular object then bail
if ( ! isset( $wp_query->query_vars['download'] ) || ! is_singular() )
return;
//Return 404 if no download link
$dl_id = intval( get_query_var( 'download' ) );
$dl_url = get_post_meta(get_the_ID(), 'repeatable_fields', true);
if($dl_val!=0 && empty($dl_url[$dl_id-1])) {
$wp_query->set_404();
status_header( 404 );
get_template_part( 404 );
exit();
}
// include custom template
include get_template_directory().'/vietrick/download.php';
exit;
}
add_action( 'template_redirect', 'themes_download_template' );
However, I also want to remove the child category from URL with following code:
function remove_child_categories_from_permalinks( $category ) {
while ( $category->parent ) {
$category = get_term( $category->parent, 'category' );
}
return $category;
}
add_filter( 'post_link_category', 'remove_child_categories_from_permalinks', 999 );
The code work for:
- domain.com/top-category/post-slug/
- domain.com/top-category/child-category/post-slug/download
But the custom endpoint does not work for:
- domain.com/top-category/post-slug/download
Anyone has any idea?
post_link_category
filter is ignoring the second parameter in that filter which may be related to this