首页  >  问答  >  正文

WordPress add_rewrite_rule 自定义帖子类型如何正确设置

我的 wp 博客有一个名为“rules_and_laws”的自定义帖子类型,并且我添加了一个函数来指定重写规则:

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

该规则适用于自定义帖子类型“rules_and_law”,唯一的问题是现在博客的所有其他页面和帖子都返回 404。

我尝试了另一种方法,尝试仅对 cpt 'rules_and_laws' 应用重写 url,但没有任何效果:

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

例如,对于此代码,规则根本没有应用(看起来 is_singular('rules_and_laws') 不起作用)。

这是基本网址的示例:

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

这就是重写:

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

感谢您的帮助。

P粉587970021P粉587970021251 天前335

全部回复(1)我来回复

  • P粉514458863

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

    应解决该问题的代码更新版本:

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

    回复
    0
  • 取消回复