Skip to content

Instantly share code, notes, and snippets.

@akiya64
Last active May 13, 2023 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akiya64/a5bebd20d6d9f9ca03cd720b0859f9e9 to your computer and use it in GitHub Desktop.
Save akiya64/a5bebd20d6d9f9ca03cd720b0859f9e9 to your computer and use it in GitHub Desktop.
Simple URL structure by simple rewrite rule
<?php
function my_post_type() {
register_post_type(
'news',
array(
'public' => true,
'has_archive' => true,
'rewrite' => array(
'with_front' => false,
'slug' => 'my-post-type'
)
)
);
}
add_action( 'init', 'my_post_type' );
// /my-post-type/1234/ Show post by ID but default slug.
function add_mypostype_rewrite_tag( $post_type ){
if('my_post_type' === $post_type) {
add_rewrite_tag('%my_post_type_id%', '([0-9]+)', 'post_type=my_post_type&p=');
// Set diffrent name from post type.
add_permastruct('my_post_type_id', 'my-post-type/%my_post_type_id%' );
}
}
add_action('registered_post_type', 'add_mypostype_rewrite_tag', 10, 1 );
// Convert output url by the_permalink() etc.
function my_post_type_link( $link, $post ){
if ( 'my_post_type' !== $post->post_type ) {
return $link;
}
return home_url( '/my-post-type/' . $post->ID );
}
add_filter( 'post_type_link', 'my_post_type_link', 1, 2 );
// Set url structure /<custom_post_type>/<term>/
register_taxonomy(
'my_taxonomy',
array(
'public' => true,
'show_ui' => true,
'show_in_rest' => true,
'capability_type' => 'my_post_type',
'rewrite' => false,
)
);
add_action( 'init', function(){
add_rewrite_tag( '%my_type_tax%','([^/]+', 'post_type=my_custom_type&my_taxonomy=' );
add_permastruct( 'my_custom_type_term', '/my-post-type/%my_type_tax%', array( 'with_front'=>false));
}, 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment