0

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?

1
  • have you resaved permalinks and have you ran the new URL through a rewrite rules debugger to see which rule actually picks up your URL? Also your post_link_category filter is ignoring the second parameter in that filter which may be related to this
    – Tom J Nowell
    Oct 2, 2022 at 11:27

1 Answer 1

0

Disable the Canonical redirect will keep the code work:

function disable_canonical_redirect_for_download_page( $redirect ) {
    if ( isset( $wp_query->query_vars['download'] ) || is_singular() ) {
            $redirect = false;
    }

    return $redirect;
}
add_filter( 'redirect_canonical', 'disable_canonical_redirect_for_download_page' );
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Oct 14, 2022 at 7:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.