Skip to content

Instantly share code, notes, and snippets.

@danielbachhuber
Created July 3, 2014 14:40
Show Gist options
  • Save danielbachhuber/8af274e2b7f21c8c3bb6 to your computer and use it in GitHub Desktop.
Save danielbachhuber/8af274e2b7f21c8c3bb6 to your computer and use it in GitHub Desktop.
Post-style permalinks for your custom post types
<?php
/**
* Post-style permalinks for your custom post types
* e.g. %year%/%monthnum%/%day%/%postname%
*/
function dbx_get_post_types() {
return array(
// replace with your custom post types
'my-custom-post-type'
);
}
/**
* Turns any CPT link into the post-style link
*/
function dbx_filter_post_type_link( $link, $post ) {
if ( in_array( $post->post_type, dbx_get_post_types() ) ) {
$query = parse_url( $link, PHP_URL_QUERY );
parse_str( $query, $args );
// Generating a preview link
if ( ! empty( $args['post_type'] ) && $args['post_type'] === $post->post_type ) {
return $link;
}
$unixtime = strtotime( $post->post_date );
$date = explode( " ",date( 'Y m d H i s', $unixtime ) );
// Sometimes the permalink is passed for preview links
if ( 'publish' === $post->post_status && $post->post_name ) {
$post_name = $post->post_name;
} else {
$post_name = '%' . $post->post_type . '%';
}
$search_replace = array(
'%year%' => $date[0],
'%monthnum%' => $date[1],
'%day%' => $date[2],
'%postname%' => $post_name,
);
$permalink_struct = '%year%/%monthnum%/%day%/%postname%/';
$link = home_url( str_replace( array_keys( $search_replace ), array_values( $search_replace ), $permalink_struct ) );
}
return $link;
}
add_filter( 'post_type_link', 'dbx_filter_post_type_link', 10, 2 );
/**
* Set the appropriate rewrite rules
*/
function dbx_post_type_rewrites() {
$post_types = '';
foreach( dbx_get_post_types() as $ptype ) {
$post_types .= '&post_type[]=' . $ptype;
}
add_rewrite_rule( '([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)/page/?([0-9]{1,})/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]&paged=$matches[5]' . $post_types, 'top' );
add_rewrite_rule( '([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/([^/]+)(/[0-9]+)?/?$', 'index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]&page=$matches[5]' . $post_types, 'top' );
// Rewrite rules we don't want
add_filter( 'post_rewrite_rules', '__return_empty_array' );
foreach( dbx_get_post_types() as $post_type ) {
add_filter( "{$post_type}_rewrite_rules", '__return_empty_array' );
}
}
add_action( 'init', 'dbx_post_type_rewrites' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment