Skip to content

Instantly share code, notes, and snippets.

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 saqibsarwar/34ddf5a74ac1ba603a21e0a53aad98a3 to your computer and use it in GitHub Desktop.
Save saqibsarwar/34ddf5a74ac1ba603a21e0a53aad98a3 to your computer and use it in GitHub Desktop.
Replace Property Slug in URL with Property ID
<?php
/**
* Add new rewrite for post type
* Add permalink structure
*/
function _post_type_rewrite() {
global $wp_rewrite;
// Set the query arguments used by WordPress
$queryarg = 'post_type=property&p=';
// Concatenate %cpt_id% to $queryarg (eg.. &p=123)
$wp_rewrite->add_rewrite_tag( '%cpt_id%', '([^/]+)', $queryarg );
// Add the permalink structure
$wp_rewrite->add_permastruct( 'property', '/property/%cpt_id%/', false );
}
add_action( 'init', '_post_type_rewrite' );
/**
* Replace permalink segment with post ID
*
*/
function _post_type_permalink( $post_link, $id = 0, $leavename ) {
global $wp_rewrite;
$post = get_post( $id );
if ( is_wp_error( $post ) )
return $post;
// Get post permalink (should be something like /some-type/%cpt_id%/
$newlink = $wp_rewrite->get_extra_permastruct( 'property' );
// Replace %cpt_id% in permalink structure with actual post ID
$newlink = str_replace( '%cpt_id%', $post->ID, $newlink );
$newlink = home_url( user_trailingslashit( $newlink ) );
return $newlink;
}
add_filter('post_type_link', '_post_type_permalink', 1, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment