Skip to content

Instantly share code, notes, and snippets.

@userabuser
Last active December 17, 2021 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save userabuser/88fe4dcddae8a905e937df0a1e9c5486 to your computer and use it in GitHub Desktop.
Save userabuser/88fe4dcddae8a905e937df0a1e9c5486 to your computer and use it in GitHub Desktop.
Allow products and terms from multiple taxonomies to share rewrite base /product for rule
<?php
// option 1
add_action('parse_request', function () {
global $wp_rewrite, $wp, $wp_query;
if (isset($wp->query_vars['product'], $wp->query_vars['post_type']) && $wp->query_vars['post_type'] === 'product') {
$matched = false;
$term_name = $wp->query_vars['product'];
$taxonomy_1 = 'product_type';
$taxonomy_2 = 'product_size';
if (($exists = term_exists($term_name, $taxonomy_1)) && isset($exists['term_id'])) {
$matched = true;
$taxonomy = $taxonomy_1;
} elseif (($exists = term_exists($term_name, $taxonomy_2)) && isset($exists['term_id'])) {
$matched = true;
$taxonomy = $taxonomy_2;
}
if ($matched) {
$wp->query_vars = array(
$taxonomy => $term_name,
);
}
}
});
// option 2
add_action('pre_get_posts', function ($query) {
if ($query->is_main_query()) {
if (get_query_var('post_type') === 'product' && ($term_name = get_query_var('product'))) {
$matched = false;
$taxonomy_1 = 'product_type';
$taxonomy_2 = 'product_size';
if (($exists = term_exists($term_name, $taxonomy_1)) && isset($exists['term_id'])) {
$matched = true;
$taxonomy = $taxonomy_1;
} elseif (($exists = term_exists($term_name, $taxonomy_2)) && isset($exists['term_id'])) {
$matched = true;
$taxonomy = $taxonomy_2;
}
if ($matched) {
$query->query = array($taxonomy => $term_name);
unset($query->query_vars['page']);
unset($query->query_vars['product']);
unset($query->query_vars['post_type']);
// reset all flags
$query->init_query_flags();
$query->is_tax = true;
$query->is_archive = true;
$query->set('name', '');
$query->set($taxonomy, $term_name);
// we need to call parse_tax_query again to have the tax_query property
// on WP_Query class populated based on the query vars set above
/** @var \WP_Query $query */
$query->parse_tax_query($query->query_vars);
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment