Created
July 8, 2024 21:56
-
-
Save stoph/519ecc72fc5d7856a8e4b79d8724e8d2 to your computer and use it in GitHub Desktop.
Dynamic URL parameters for WP pages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: Dynamic Parameters | |
*/ | |
$dynamic_page_slugs = [ | |
'product-detail' => [ // product-detail/12345/awesome_product | |
'product_id' => '(\d+)', | |
'product_name' => '([a-zA-Z0-9-_]+)', | |
], | |
]; | |
/* | |
The above example for /product-details/12345/awesome_product/ would produce... | |
Regex: product-detail/(\d+)/([a-zA-Z0-9-_]+) | |
Query: index.php?pagename=product-detail&vip_composable_params=product_id:$matches[1]|product_name:$matches[2] | |
String: product_id:12345|product_name:awesome_product | |
Params array: | |
[product_id] => 12345 | |
[product_name] => awesome_product | |
*/ | |
add_filter('query_vars', function ($vars) { | |
$vars[] = 'vip_composable_params'; | |
return $vars; | |
}); | |
add_action('init', function() use ($dynamic_page_slugs) { | |
// create a rule for each dynamic page | |
foreach ($dynamic_page_slugs as $slug => $params) { | |
$regex = $slug . '/'; // Start with the slug | |
$query = 'index.php?pagename=' . $slug; // Start building the query string | |
$vip_composable_params = []; | |
$i = 1; // Start matches from 1 | |
foreach ($params as $param => $pattern) { | |
$regex .= $pattern; | |
$vip_composable_params[] = $param . ':$matches[' . $i . ']'; | |
$i++; | |
if ($i <= count($params)) { | |
$regex .= '/'; | |
} | |
} | |
if ($regex[-1] === '/') { | |
$regex = rtrim($regex, '/'); | |
} | |
$query .= '&vip_composable_params=' . implode('|', $vip_composable_params); | |
echo "<b>Regex:</b> $regex<br>"; | |
echo "<b>Query:</b> $query<br>"; | |
add_rewrite_rule( | |
'^' . $regex . '/?$', | |
$query, | |
'top' | |
); | |
} | |
// Force flush rewrite rules every page load :) | |
flush_rewrite_rules(); | |
}); | |
// Flush rewrite rules on plugin activation | |
// Not a good option because the code could change without the plugin being reactivated. | |
register_activation_hook(__FILE__, function () { | |
flush_rewrite_rules(); | |
}); | |
// Display params | |
add_action('template_redirect', function() { | |
$params_string = get_query_var('vip_composable_params'); | |
$params = []; | |
// echo "<b>String:</b> $params_string<br>"; | |
if (!empty($params_string)) { | |
$param_pairs = explode('|', $params_string); | |
foreach ($param_pairs as $pair) { | |
list($key, $value) = explode(':', $pair); | |
$params[$key] = $value; | |
} | |
echo '<pre>Params ' . print_r($params, true) . '</pre>'; | |
} else { | |
echo 'No parameters provided.'; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment