There are so many ways to play around with the custom post type permalink structure in WordPress. However, in this post I will show you how to re-write the custom post type permalink structure with post id ahead of the post title. Sounds complex? Well, let’s take a look at the following sample URL structure of a custom post type (books).
https://urdomain.com/books/334/your-post-title/
This is what exactly we are talking about here. According to the URL structure, we have registered a custom post type called “books” first. In case if you don’t know, read this article to learn how to register a custom post type in WP, so check it out.
However, while registering for a CPT you should change the rewrite argument of the register_post_type function with the following line to make it work properly.
'rewrite' => array('slug' => 'books/%post_id%', 'with_front' => false),
Once you are done with modifying the rewrite argument, add the following snippet on your theme’s functions.php file.
<?php
function rewrite_books_url($post_link,$post = 0,$leavename = false) {
if ( strpos('%post_id%', $post_link) === 'false' ) {
return $post_link; }
if ( is_object($post) ) {
$post_id = $post->ID;
} else {
$post_id = $post;
$post = get_post($post_id); }
if ( !is_object($post) || $post->post_type != 'books' ) {
return $post_link; }
return str_replace('%post_id%',$post_id, $post_link); }
add_filter('post_type_link','rewrite_books_url', 1, 3);
?>
If you want to apply this snippet to work with your desired CPT, make sure to change the word “books” with your desired CPT name on line 10. That should do the trick.
Comment
Leave a Reply