Skip to content

Instantly share code, notes, and snippets.

@chwnam
Created July 30, 2021 10:23
Show Gist options
  • Save chwnam/f82eb9bda48f18798dc189835cecb290 to your computer and use it in GitHub Desktop.
Save chwnam/f82eb9bda48f18798dc189835cecb290 to your computer and use it in GitHub Desktop.
Modify CPT URL permastructure
<?php
/**
* Plugin Name: My CPT with custom permalink.
* Description: Change permalink from /cpt/%postname% to /cpt/%post_id%.
*/
add_action( 'init', 'my_cpt_init' );
function my_cpt_init() {
register_post_type(
'my-cpt',
[
'label' => 'My CPT',
'public' => true,
'hierarchical' => false,
'rewrite' => [
'slug' => 'cpt',
'pages' => true,
'feeds' => false,
'ep_mask' => EP_NONE,
],
'has_archive' => true,
'show_in_rest' => true,
]
);
}
add_action( 'registered_post_type', 'my_cpt_registered_post_type', 10, 2 );
function my_cpt_registered_post_type( string $post_type, WP_Post_Type $post_type_object ) {
global $wp_rewrite;
if ( 'my-cpt' === $post_type ) {
$wp_rewrite->extra_permastructs[ $post_type ]['struct'] =
$wp_rewrite->front . $post_type_object->rewrite['slug'] . '/%post_id%';
}
}
add_filter( 'post_type_link', 'my_cpt_post_type_link', 10, 2 );
function my_cpt_post_type_link( string $post_link, WP_Post $post ): string {
if ( 'my-cpt' === $post->post_type ) {
$post_link = str_replace( '%post_id%', $post->ID, $post_link );
}
return $post_link;
}
add_filter( 'rewrite_rules_array', 'my_cpt_rewrite_rules_array' );
function my_cpt_rewrite_rules_array( array $rules ): array {
$obj = get_post_type_object( 'my-cpt' );
if ( $obj ) {
$slug = $obj->rewrite['slug'];
$new_rules = [
$slug . '/([0-9]+)/page/?([0-9]{1,})/?$' => 'index.php?post_type=my-cpt&p=$matches[1]&paged=$matches[2]',
$slug . '/([0-9]+)(?:/([0-9]+))?/?$' => 'index.php?post_type=my-cpt&p=$matches[1]&page=$matches[2]',
];
foreach ( $new_rules as $key => $value ) {
if ( isset( $rules[ $key ] ) ) {
$rules[ $key ] = $value;
}
}
}
return $rules;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment