Wordpress - Access the same page from multiple urls (wildcard)

You can use template_include, but before you hook to this filter you must do the following steps:

  1. Create page template. e.g: page-target.php

    <?php
    /**
     * Template Name: Page Target
     */
    ...
    
  2. Manually query the contents of target-page on page-target.php template, because the global $post will be referencing to your some-prefix-* page.

  3. (Optional): Edit and apply page template Page Target to your /target-page from the Page Attributes

Then add the following to your functions.php file

add_filter('template_include', function($template) {
    global $post;

    $prefix = 'some-prefix-'; // Your prefix
    $prefixExist = strpos($post->post_name, $prefix) !== false;

    if ($prefixExist) {
        return locate_template('page-target.php'); //Your template
    }

    return $template;
});

Above filter will override the template with page-target.php if condition met, otherwise default

Edit:

I think I have found a better way to resolve this using add_rewrite_rule

function custom_rewrite_basic() {
  $page_id = 123; //Your serve page id
  add_rewrite_rule('^some-prefix-.*', 'index.php?page_id=' . $page_id, 'top');
}
add_action('init', 'custom_rewrite_basic');

IMPORTANT: Do not forget to flush and regenerate the rewrite rules database after modifying rules. From WordPress Administration Screens, Select Settings -> Permalinks and just click Save Changes without any changes.


Note that search engines might not like multiple paths to the same content!

Here I assume you want e.g.:

example.tld/some/path/to/painting-orange
example.tld/painting-blue
example.tld/painting-red
example.tld/painting-yellow

to behave like it was this page:

example.tld/paintings

but not so for paths like:

example.tld/painting-white/painting-brown/large
example.tld/painting-brown/small

The rule here is to match the prefix on the left side of basename( $path ).

Here's a little hack with the request filter, to check if the current page name is correctly prefixed:

<?php
/** 
 * Plugin Name: Wildcard Pages
 */
add_filter( 'request', function( $qv )
{
    // Edit to your needs
    $prefix = 'painting-';
    $target = 'paintings';

    // Check if the current page name is prefixed
    if(    isset( $qv['pagename'] )
        && $prefix === substr( basename( $qv['pagename'] ), 0, strlen( $prefix ) ) 
    )
        $qv['pagename'] = $target;

    return $qv;
} );

Modify this to your needs. Then create the plugin file /wp-content/plugins/wpse-wildcard-pages/wpse-wildcard-pages.php file and activate the plugin from the backend.

We could also add a check with get_page_by_path() on the target page, just to make sure it exists. We might also want to restrict this to certain post types.

Tags:

Pages

Urls