Last active
July 16, 2020 14:29
-
-
Save mrpatg/42628f83aada824cb169e8ea7ee28ccf to your computer and use it in GitHub Desktop.
rewrite hell
This file contains hidden or 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 | |
function features_rewrite_link($post_link, $id = 0) | |
{ | |
$post = get_post($id); | |
if ( is_object( $post ) && $post->post_type == 'features' ){ | |
$terms = wp_get_object_terms($post->ID, 'product_cats'); | |
if ($terms) { | |
return str_replace('%category%', $terms[0]->slug, $post_link); | |
} | |
} | |
return $post_link; | |
} | |
add_filter('post_type_link', 'features_rewrite_link', 1, 3); | |
add_filter( 'post_type_link', function($post_link, $post, $leavename) { | |
if ('products' == $post->post_type && 'publish' == $post->post_status) { | |
$post_link = site_url('/') . $post->post_name .'/'; | |
} | |
return $post_link; | |
}, 10, 3 ); | |
function resources_cpt_generating_rule($wp_rewrite) { | |
$rules = array(); | |
$terms = get_terms( array( | |
'taxonomy' => 'product_cats', | |
'hide_empty' => false, | |
) ); | |
$post_type = 'features'; | |
foreach ($terms as $term) { | |
$rules[$term->slug . '/([^/]*)$'] = 'index.php?post_type=' . $post_type. '&name=$matches[1]'; | |
} | |
// merge with global rules | |
$wp_rewrite->rules = $rules + $wp_rewrite->rules; | |
} | |
add_filter('generate_rewrite_rules', 'resources_cpt_generating_rule'); | |
add_action( 'parse_request', function ( $wp ) { | |
// if we get a products request, we check if it is actually a product, if not it's a root level page, and we fix that in the vars | |
if ( array_key_exists('products', $wp->query_vars) && array_key_exists('page', $wp->query_vars) ) { | |
$custom_post = get_page_by_path( $wp->request, OBJECT); | |
if ( $custom_post instanceof WP_Post ) { | |
$terms = get_terms( array( | |
'taxonomy' => 'product_cats', | |
'hide_empty' => false, | |
) ); | |
foreach ($terms as $term) { | |
$products_array[] = $term->slug; | |
} | |
if(empty(array_intersect($products_array, $wp->query_vars))){ | |
unset($wp->query_vars['error'] ); | |
unset($wp->query_vars['features']); | |
unset($wp->query_vars['post_type']); | |
unset($wp->query_vars['products']); | |
$wp->query_vars['post_type'] = 'page'; | |
$wp->query_vars['page'] = $wp->query_vars['name']; | |
} | |
} | |
} | |
// sometimes it kicks other post out as attachments, we handle that here as needed | |
if ( array_key_exists('attachment', $wp->query_vars)) { | |
$post_object = get_page_by_path($wp->query_vars['attachment'],OBJECT,'post'); | |
$wp->query_vars['post_type'] = $post_object->post_type; | |
$wp->query_vars['name'] = $post_object->post_name; | |
} | |
return $wp; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment