Created
March 1, 2017 09:38
-
-
Save azizultex/30e7dd0b283d8217b9154216f507b332 to your computer and use it in GitHub Desktop.
Custom Post Type URL Rewrite Made Easy!
This file contains 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
/* | |
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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you are looking to change slug of custom post type or taxonomy. Please follow: https://gist.github.com/azizultex/2f8340c2c2c7ea18b6be57aadfc3ab76