Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created June 6, 2018 13:47
Show Gist options
  • Save tommcfarlin/d80f687b25281f1ab7c9390cf56d2187 to your computer and use it in GitHub Desktop.
Save tommcfarlin/d80f687b25281f1ab7c9390cf56d2187 to your computer and use it in GitHub Desktop.
[WordPress] Working with Custom Rewrite Rules and Page Templates in WordPress
<?php
$query = $this->query->query([
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'meta_value' => ['template-alpha.php', 'template-beta.php'],
]);
if (!$query) {
return;
}
// More to come...
<?php
foreach ($query as $post) {
$slug = get_page_template_slug($post->ID);
if ('template-alpha.php' === $slug) {
$this->alphaPages[] = $post;
}
if ('template-find-a-camp.php' === $slug) {
$this->betaPages[] = $post;
}
}
<?php
add_rewrite_tag('%country%', '([^&]+)');
add_rewrite_tag('%state%', '([^&]+)');
foreach ($this->alphaPages as $post) {
add_rewrite_rule(
'^'.$post->post_name.'/([^/]*)/([^/]*)/?',
'index.php?page_id='.$post->ID.'&country=$matches[1]&state=$matches[2]',
'top'
);
add_rewrite_rule(
'^'.$post->post_name.'/([^/]*)/?',
'index.php?page_id='.$post->ID.'&country=$matches[1]',
'top'
);
}
<?php
add_rewrite_tag('%acme-id%', '([^&]+)');
foreach ($this->betaPages as $post) {
add_rewrite_rule(
'^(.*)?/([A-Za-z0-9-]+-)(\d+)/?',
'index.php?page_id='.$post->ID.'&acme-id=$matches[3]',
'top'
);
}
<?php
public function addRewriteRules()
{
$query = $this->query->query([
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'meta_value' => ['template-alpha.php', 'template-beta.php'],
]);
if (!$query) {
return;
}
$this->setPageTypes($query);
$this->setAlphaRewriteRules();
$this->setBetaRewriteRules();
}
private function setPageTypes($query)
{
foreach ($query as $post) {
$slug = get_page_template_slug($post->ID);
if ('template-alpha.php' === $slug) {
$this->alphaPages[] = $post;
}
if ('template-find-a-camp.php' === $slug) {
$this->betaPages[] = $post;
}
}
}
private function setAlphaRewriteRules()
{
add_rewrite_tag('%country%', '([^&]+)');
add_rewrite_tag('%state%', '([^&]+)');
foreach ($this->alphaRules as $post) {
add_rewrite_rule(
'^'.$post->post_name.'/([^/]*)/([^/]*)/?',
'index.php?page_id='.$post->ID.'&country=$matches[1]&state=$matches[2]',
'top'
);
add_rewrite_rule(
'^'.$post->post_name.'/([^/]*)/?',
'index.php?page_id='.$post->ID.'&country=$matches[1]',
'top'
);
}
}
private function setBetaRewriteRules()
{
add_rewrite_tag('%acme-id%', '([^&]+)');
foreach ($this->betaPages as $post) {
add_rewrite_rule(
'^(.*)?/([A-Za-z0-9-]+-)(\d+)/?',
'index.php?page_id='.$post->ID.'&acme-id=$matches[3]',
'top'
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment