Created
May 15, 2025 08:52
-
-
Save mehrshaddarzi/8fcbefca77900f2cd6cc2471e37f3661 to your computer and use it in GitHub Desktop.
add Post Id before Custom Post Type Slug in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 1. Modify the generated permalink | |
function custom_post_type_permalink($post_link, $post) { | |
if ('download' == $post->post_type) { | |
$post_link = home_url( | |
user_trailingslashit("downloads/{$post->ID}/{$post->post_name}") | |
); | |
} | |
return $post_link; | |
} | |
add_filter('post_type_link', 'custom_post_type_permalink', 10, 2); | |
// 2. Add rewrite rules to handle the new URL structure | |
function custom_post_type_rewrite_rules() { | |
// Main rewrite rule | |
add_rewrite_rule( | |
'downloads/([0-9]+)/([^/]+)/?$', | |
'index.php?post_type=download&p=$matches[1]', | |
'top' | |
); | |
// Pagination support | |
add_rewrite_rule( | |
'downloads/([0-9]+)/([^/]+)/page/([0-9]{1,})/?$', | |
'index.php?post_type=download&p=$matches[1]&paged=$matches[3]', | |
'top' | |
); | |
} | |
add_action('init', 'custom_post_type_rewrite_rules'); | |
function prevent_slug_modification_for_cpt($override_slug, $slug, $post_ID, $post_status, $post_type, $post_parent) { | |
// Only apply to our custom post type | |
if ('download' === $post_type) { | |
// Return the original slug without modification | |
return $slug; | |
} | |
// Let WordPress handle other post types normally | |
return $override_slug; | |
} | |
add_filter('pre_wp_unique_post_slug', 'prevent_slug_modification_for_cpt', 10, 6); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment