最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

url rewriting - Custom Post Type parentchild relationship rewrite rules for permalinks

matteradmin6PV0评论

I have been working on this for quite awhile but I'm stuck at rewriting the permalinks for both the parent and the child.

So I created two custom post types: magazines and magazine-pages both MUST be hierarchical. Also magazine-pages is part of the magazine custom post type:

Here's my code for that:

// Magazines
    $args = array(
        'label' => 'Magazines',
        'labels' => array(
            //my-labels
        ),
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 25,
        'hierarchical' => true,
        'query_var' => true,
        'rewrite' => array( "slug" => "magazines" ),
        'supports' => array('title', 'thumbnail'),
        'menu_icon'   => 'dashicons-book'
    );

    register_post_type('magazines', $args);

    // Magazine pages
    $args = array(
        'label' => 'Magazine pages',
        'labels' => array(
            //my-labels
        ),
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'hierarchical' => true,
        'query_var' => true,
        "rewrite" => array( "slug" => "magazines" ),
        'supports' => array('title', 'thumbnail', 'editor'),
        'show_in_menu' => 'edit.php?post_type=magazines'
    );

    register_post_type('magazine-pages', $args);
}

What I'm trying to achieve:

/magazines/magazine-1/magazine-page-1

Where

/magazine-1 Should be a post from CPT magazine (parent)

and

/magazine-page-1 Should be a post from CPT magazine-pages (child)

I did add the following rewrite rules to make this work, but unfortunately it doesn't. Only the parent page works, the child pages returns a 404 error.

add_action( 'init', function() {
    add_rewrite_rule( '^magazines/([^/]*)/?','index.php?magazines=$matches[1]','top' );
    add_rewrite_rule( '^magazines/([^/]*)/([^/]*)/?','index.php?magazine-pages=$matches[2]','top' ); 
});

Did I do something wrong in the rewrite rules? All the help is welcome!

Post a comment

comment list (0)

  1. No comments so far