URL rewrites for custom post type permalinks in WordPress

I was recently remaking rewrite rules for my project – https://sochi.asp.sale/. The idea was to use post-types in url as well as custom post metas to form url containing

/real-estate/location/deal type or property type/

Here is the example code, I’m using, basically in 3 steps:

  1. Removing the permalink, that was set by theme developer
  2. Creating rewrite rules
  3. Making sure they will be used in all links
// Remove old rules

add_action( "after_setup_theme", 'custom_remove_permalink', 1);
function custom_remove_permalink(){
remove_action( "after_setup_theme", 'active_permalinks');
}

// Create custom rules

add_action( "after_setup_theme", 'custom_active_permalinks');
function custom_active_permalinks() {
global $wp_rewrite;
$wp_rewrite->add_rewrite_tag("%custompost%", '([^/]+)', "custompost=");
$wp_rewrite->add_rewrite_tag( "%custompost-type%", '(.+?)', "custompost-type=" );
$wp_rewrite->add_rewrite_tag( "%companies%", '(.+?)', "companies=" );
$rewrite_args = array();
$rewrite_args['walk_dirs'] = false;
add_rewrite_rule( '([^/]+)/projects/?$', 'index.php?category_name=$matches[1]&post_type=custompost', 'top' );
$wp_rewrite->add_permastruct('custompost', '%companies%/projects/%custompost%', $rewrite_args);

}

// Make sure that all links on the site, include the related texonomy terms

add_filter( 'post_type_link', 'custom_custompost_permalink', 10, 2 );
function custom_custompost_permalink( $permalink, $post ) {
if ( $post->post_type !== 'custompost' ) {
return $permalink;
}

$companies = get_post_meta($post->ID, 'company', true );

if ( ! $companies ) {
$permalink = str_replace( '%companies%', 'defaultvalue', $permalink );
} else {
$permalink = str_replace( '%companies%', $companies , $permalink );
}

$terms = wp_get_post_terms($post->ID, 'custompost-type', array( 'orderby' => 'parent', 'order' => 'DESC' ));

if ( ! $terms ) {
$permalink = str_replace( '%custompost-type%', '_yoast_wpseo_primary_category', $permalink );
} else {
$permalink = str_replace( '%custompost-type%', $terms[0]->slug , $permalink );
}

$authordata = get_userdata($post->post_author);
$author = $authordata->user_nicename;
if ( ! $author ) {
$permalink = str_replace( '%author%', 'author', $permalink );
} else {
$permalink = str_replace( '%author%', $author , $permalink );
}

return $permalink;
}
Follow Sam Tyurenkov:
Hi there, I'm a web-designer, marketing and product manager, business developer. I have created this website and about 25 others. I'm also doing various tasks for IT projects besides websites - like mobile games.