Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save atomtigerzoo/1cbd9bbcd349d0ff37dd0faf049b2cd5 to your computer and use it in GitHub Desktop.
Save atomtigerzoo/1cbd9bbcd349d0ff37dd0faf049b2cd5 to your computer and use it in GitHub Desktop.
<?php
/*
This specific case creates a new route/URl to display Wordpress
posts from a fixed category with a parameter-based taxonomy
term with a custom template.
Needs template file: custom-template_category-tax_term.php
Inside the template you can fetch the query-var with:
$wp_query->get('my_tax_query_var')
Change these to your likings:
- my_new_route
- my_tax_query_var
- my_taxonomy_name
- $query->set('cat', 1);
*/
/**
* Create Rewrite-rule / Route
* /my_new_route/[taxonomy_term]
*/
add_action('init', function() {
add_rewrite_rule(
'^my_new_route/([a-z0-9-]+)[/]?$',
'index.php?my_tax_query_var=$matches[1]',
'top'
);
});
/**
* Create new query var
*/
add_filter('query_vars', function ($query_vars){
$query_vars[] = 'my_tax_query_var';
return $query_vars;
});
/**
* Use specific template when query_var 'my_tax_query_var' is set
*/
add_action('template_include', function($template) {
if(get_query_var('my_tax_query_var') == false || get_query_var('my_tax_query_var') == '') {
return $template;
}
// Check for given term, fail/404 if not found
$tax_term = get_terms([
'taxonomy' => 'my_taxonomy_name',
'slug' => get_query_var('my_tax_query_var')
]);
if(!$tax_term || empty($tax_term)) {
status_header(404);
get_template_part(404);
exit();
}
return get_template_directory() . '/custom-template_category-tax_term.php';
});
/**
* Modify the main query of the new template to only include
* the correct posts
*/
add_action('pre_get_posts', function($query) {
if(!is_admin() && $query->is_main_query()) {
if(get_query_var('my_tax_query_var') == false || get_query_var('my_tax_query_var') == '') {
// do nothing...
} else{
// Set the fixed category
$query->set('cat', 1);
// Ignore stickies
$query->set('ignore_sticky_posts', true);
// Create topic_term tax query
$tax_query_topic_term = [[
'taxonomy' => 'my_taxonomy_name',
'field' => 'slug',
'terms' => get_query_var('my_tax_query_var')
]];
$query->set('tax_query', $tax_query_topic_term);
return;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment