Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

Wordpress add_rewrite_rule for custom post type how to set correctly

Writer Andrew Mclaughlin

i have a custom post type for my wp blog called 'rules_and_laws' and I have added a function to specify a rewrite rule:

 function custom_rules_and_laws_permalink_structure() { add_rewrite_rule( '([^/]+)/?$', 'index.php?rules_and_laws=$matches[1]', 'top' ); }
add_action( 'init', 'custom_rules_and_laws_permalink_structure' );

The rule works ok for custom post type 'rules_and_law', the only problem is that now all the other pages and posts of the blog return 404.

I tried another approach trying to apply the rewrite url only for cpt 'rules_and_laws' but nothing worked:

function custom_rules_and_laws_permalink_structure() { // Check if the current post type is 'rules_and_laws' if (is_singular('rules_and_laws')) { add_rewrite_rule( '([^/]+)/?$', 'index.php?rules_and_laws=$matches[1]', 'top' ); flush_rewrite_rules(); // Flush the rewrite rules to apply the changes }
}
add_action('init', 'custom_rules_and_laws_permalink_structure');

for example with this code the rules was not applied at all ( looks like is_singular('rules_and_laws') don't work ).

This is an example of base url:

and that's the rewrite:

Thank you for your help.

1 Answer

an updated version of your code that should address the issue:

function custom_rules_and_laws_permalink_structure() { // Register the rewrite rule only for the 'rules_and_laws' post type add_rewrite_rule( '^rules_and_laws/([^/]+)/?$', 'index.php?rules_and_laws=$matches[1]', 'top' ); // Flush the rewrite rules to apply the changes flush_rewrite_rules();
}
add_action('init', 'custom_rules_and_laws_permalink_structure');
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.