Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save azizultex/30e7dd0b283d8217b9154216f507b332 to your computer and use it in GitHub Desktop.
Save azizultex/30e7dd0b283d8217b9154216f507b332 to your computer and use it in GitHub Desktop.
Custom Post Type URL Rewrite Made Easy!
/*
You can rewrite custom post type links anyway you want following below code. I have completely replaced CPT slug with a custom metabox field for each post type.
Resources:
1. http://wordpress.stackexchange.com/questions/83531/custom-post-type-404s-with-rewriting-even-after-resetting-permalinks
2. http://shibashake.com/wordpress-theme/custom-post-type-permalinks-part-2
*/
/* Register Custom Post Type */
function viz360_project_post_type() {
add_rewrite_tag('%client_name%','(.+)');
$labels = array();
$args = array(
'label' => __( 'Project', 'viz360' ),
'labels' => $labels,
'rewrite' => array('slug' =>'%client_name%')
);
register_post_type( 'viz360_projects', $args );
}
add_action( 'init', 'viz360_project_post_type', 0 );
/**
* get customized url by meta boxes
*/
function viz_remove_slug( $permalink, $post, $leavename ) {
if ( stripos( $permalink, '%client_name%' ) == false )
return $permalink;
if ( is_object( $post ) && 'viz360_projects' == $post->post_type ) {
$post_id = $post->ID;
$client_id = get_post_meta($post_id, 'client', true);
$var1 = basename(get_permalink($client_id));
$var1 = sanitize_title($var1);
$permalink = str_replace( '%client_name%', $var1, $permalink );
}
return $permalink;
}
add_filter( 'post_type_link', 'viz_remove_slug', 10, 3 );
function reflush_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_action( 'after_switch_theme', 'reflush_rules' );
@azizultex
Copy link
Author

If you are looking to change slug of custom post type or taxonomy. Please follow: https://gist.github.com/azizultex/2f8340c2c2c7ea18b6be57aadfc3ab76

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment