I have some custom products that need to be loaded into a specific url structure, the code is the following:
foreach ($products as $prod) {
$prod_obj = wc_get_product($prod->ID);
$categories = wp_get_post_terms($prod->ID, 'product_cat');
if (empty($categories) && is_wp_error($categories)) continue;
$custom_slug = get_field('custom_slug', $prod->ID);
add_rewrite_rule(
"^cpo/watches/$custom_slug/?$",
'index.php?post_type=product&p=' . $prod->ID . '&model=$matches[1]&size=$matches[2]&reference=$matches[3]',
'top'
);
}
the code above iterate over the $products
and then add a rewrite rule that allow to show each product under a custom permalink using an acf field, so the final structure will look like this: https://example.com/cpo/watches/foo-456-hello-world
.
Now the problem's that sometimes when I visit the url above I will get 404, so I have to flush the permalink in backend to make it working, and this is a pain. So a temporary workaround I did this:
add_action('template_redirect', function () {
if (is_404()) {
flush_rewrite_rules();
}
});
The code above check if the current page is in 404
and then refresh the rules automatically, in this way if the page is refreshed the custom product is visible.
Even though this solution "fix" the manual permalink refresh, I would like to avoid to show a 404 page to the final user, is there a way to keep the rewrite rules?