Custom permalink structure with categories and custom post types missing top level pages/posts

Question

Having some trouble with an unexpected result here:

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_categories');
        if ($terms) {
            return str_replace('%category%', $terms[0]->slug, $post_link);
        }
    }
    return $post_link;
}
add_filter('post_type_link', 'features_rewrite_link', 1, 3);

function resources_cpt_generating_rule($wp_rewrite) {
    $rules = array();
    $terms = get_terms( array(
        'taxonomy' => 'product_categories',
        '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');

The idea is that domain.com/page would attempt to check CPT of products, but not really the CPT, but a matching taxonomy of features CPT, before continuing to check pages/posts etc. Then domain.com/%category%/XXX would get re-written and pulled from the matching category for a custom post assigned therein.

This code itself is working, but any pages with a top level permalink, such as /about or /products returns a 404. I am not sure why that is happening. As far as I knew, this would try to match for the categories first, and if that failed continue to find something, a page/post etc before returning a 404.

I must be missing something.

0
, mrpatg 1 year 2020-07-14T16:10:27-05:00 0 Answers 41 views 0

Leave an answer

Browse
Browse