Search code examples
wordpresscustom-pages

Add custom frontend page without menu item - wordpress


Im trying to do something like this.

Add "custom page" without page

I know about adding a wordpress page from admin panel, Pages->Add New, and then link this page to PHP file using the slug. I've already done that. I just want to make this page work without adding it from admin panel, in case if page gets deleted from admin panel it won't work even if exists in the directory.

Please let me know if my question isn't clear enough. Any help is highly appreciated.

Thanks!

Update:

Thanks to @Mike i was able to solve the problem by modifying his code. I just had to add add_rewrite_rule() and its working good now. Don't forget to flush permalinks.

function add_application_endpoint() {
add_rewrite_endpoint( 'view', EP_PERMALINK );
 }

add_action( 'init', 'add_application_endpoint' );

function add_endpoint_queryvar( $query_vars ) {
    $query_vars[] = 'view';
    $query_vars[] = 'ptag';
    $query_vars[] = 'product_cat';

    return $query_vars;
}

add_filter( 'query_vars', 'add_endpoint_queryvar' );
add_rewrite_rule( '^view/([^/]+)/([^/]+)/?$', 'index.php?pagename=custom-product-tags&ptag=$matches[1]&product_cat=$matches[2]', 'top' );

/**
 * Setting up job app template redirect for custom end point rewrite
 */

function job_application_template_redirect() {
    global $wp_query;
    if ( $wp_query->query_vars['name'] != 'custom-product-tags' ) {
        return;
    }

    include dirname( __FILE__ ) . '/page-custom-product-tags.php';

    exit;
}

add_action( 'template_redirect', 'job_application_template_redirect' );

Solution

  • You can do it by creating a custom endpoint and setting up a template redirect in your functions.php file.. Here is an example for a job application page. With this code added to my functions.php file, if I visit '/apply' on my site, the page-job_application.php template is rendered.

    Hope this works for your needs.

    /**
     * Rewrite custom endpoint for job post applications
     */
    function add_application_endpoint() {
        add_rewrite_endpoint('apply', EP_PERMALINK);
    }
    add_action( 'init', 'add_application_endpoint');
    
    /**
     * Register our custom endpoint as a query var
     */
    function add_endpoint_queryvar( $query_vars ) {
            $query_vars[] = 'apply';
        return $query_vars;
    }
    add_filter( 'query_vars', 'add_endpoint_queryvar' );
    
    /**
     * Setting up job app template redirect for custom end point rewrite
     */
    function job_application_template_redirect() {
        global $wp_query;
    if ( ! isset( $wp_query->query_vars['apply'] ) || ! is_singular() )
        return;
    include dirname( __FILE__ ) . '/page-job_application.php';
    exit;
    }
    add_action( 'template_redirect', 'job_application_template_redirect' );