How to set WordPress add_rewrite_rule custom post type correctly
P粉587970021
P粉587970021 2024-01-16 15:31:03
0
1
384

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粉587970021
P粉587970021

reply all(1)
P粉514458863

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');
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!