1

I have a page template that I want to load, when ever my $_SERVER['REQUEST_URI'] is like this, www.site.com/link/147 where the number 147 will be variable.

i.e. I would like a call a page template, whenever my $_SERVER['REQUEST_URI'] contains /link/ in it.

1

If you can count on the URI always following the same pattern, e.g. /link/###, then you can selectively load a different template using a query variable and a rewrite (will need to flush rewrites to test):

/**
 * Register a query variable to check against for loading a template. 
 *
 * @param array $vars Registered query variables.
 * @return array (Maybe) filtered list of query variables.
 */
function wpdocs_add_query_var( $vars ) {
    $vars[] = 'my-template';
    return $vars;
}
add_filter( 'query_vars', 'wpdocs_add_query_var' );

/**
 * Register an endpoint using the new query variable.
 */
function wpdocs_add_rewrite_rule() {
    add_rewrite_rule( 'link/([0-9]+)?$', 'index.php?my-template=1', 'top' );
}
add_action( 'init', 'wpodcs_add_rewrite_rule' );

/**
 * Load a template based on the presence of a query variable in the request.
 *
 * @param string $template Template file.
 * @return string (Maybe) filtered template file path.
 */
function wpdocs_load_page_template( $template ) { 
    if ( ! is_admin() ) {
        if ( get_query_var( 'my-template' ) ) {
            $template = get_template_directory() . '/my-template.php';
        }
    }
    return $template;
}
add_filter( 'template_include', 'wpdocs_load_page_template' );
  • I got this error, Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'wpodcs_add_rewrite_rule' not found or invalid function name in /home/cashbacktoday/public_html/st/wp-includes/plugin.php on line 503 Warning: Cannot modify header information - headers already sent by (output started at /home/cashbacktoday/public_html/st/wp-includes/plugin.php:503) in /home/cashbacktoday/public_html/st/wp-includes/pluggable.php on line 1207 – hkchakladar Aug 26 '15 at 11:09
  • Did you actually create the my-template.php file in your template directory first? I'm not getting any such errors. You may need to finesse the actual /link/### endpoint depending on what rewrites you already have in place are though. There could be conflicts. – DrewAPicture Aug 26 '15 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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