Home  >  Q&A  >  body text

How to set WordPress add_rewrite_rule custom post type correctly

My wp blog has a custom post type called "rules_and_laws" and I added a function to specify the rewrite rules:

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' );

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

I tried another approach, tried applying rewrite url only to 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 are not applied at all (it looks like is_singular('rules_and_laws') doesn't work).

This is an example of a base URL:

https://website.com?rules_and_laws=art-4-security-regulation

This is rewriting:

https://website.com/art-4-security-regulation

thanks for your help.

P粉587970021P粉587970021251 days ago332

reply all(1)I'll reply

  • P粉514458863

    P粉5144588632024-01-17 11:43:14

    Updated version of code that should resolve this 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');

    reply
    0
  • Cancelreply