I am developing a plugin for my own rapid development that creates a custom post type. The ‘list’ for this post type is displayed on a specific page that is created and managed by the plugin. This page can be place anywhere within the site’s page hierarchy, so the slug for the single posts need to update if the site admin changes the list page location.
When creating the post type during the init
, I accomplish this by assigning the following rewrite rules to the custom post type (code trimmed for brevity):
$post_type_slug = "https://wordpress.stackexchange.com/" . get_page_uri( $page_id );
register_post_type( 'post_type_name',
...
'rewrite' => array( 'slug' => $post_type_slug, 'with_front' => true),
...
)
);
This seems to work perfectly for setting everything up initially. When the user saves the ‘list’ page, I run the following code to update the rewrite rules:
add_action( 'save_post', array(__CLASS__, 'flush_permalinks'), 2000 );
function flush_permalinks( $post_id ) {
if($post_id == get_option( $custom_page_id )){
flush_rewrite_rules(false);
}
}
However, when the user changes the location of the page, the newly updated permalinks return 404 (even though the list page displays the links correctly). But if I save the page a second time, it works perfectly! I’ve attempted changing the priority of the save_post
action (from 1 to 2000), but that does not seem to make a different. I’ve also tried to both hard and soft flush the rewrite rules, but that doesn’t change the two-save (first save doesn’t change the rewrite rules, but the second does) behavior either.
Any suggestions on what I might be doing wrong?