1

Is there a way to use exactly the same date-based permalink structure for all (non-hierachical) post types on a site, including posts and custom post types?

I'd like all post types to have the format /%year%/%monthnum%/%day%/%postname%/, so the post type does not appear in the URL.

With the default custom post type permalink structure, the following code successfully strips out the post type from the permalink (at the risk of causing problems with clashing post names, but I can live with that), but I can't figure out what I need to do to set the permalink to use the date structure.

class simons_permalinks {

    function __construct() {

        add_action( 'pre_get_posts',  array( $this, 'pre_remove_slug' ) );
        add_filter( 'post_type_link', array( $this, 'remove_slug' ), 10, 3 );

    }

    function pre_remove_slug( $query ) {

        if ( ! $query->is_main_query() )
            return;

        if ( 2 != count( $query->query ) or !isset( $query->query[ 'page' ] ) )
            return;

        $types = array( 'page', 'post', 'feature', 'opinion' );

        if ( ! empty( $query->query[ 'name' ] ) ) {
            $query->set( 'post_type', $types );
        }

    }

    function remove_slug( $link, $post, $name ) {

        $types = array( 'post', 'feature', 'opinion' );

        if ( 'post' != $post->post_type and in_array( $post->post_type, $types ) and 'publish' == $post->post_status ) {
            $pto = get_post_type_object( $post->post_type );
            $link = str_replace( '/' . $pto->rewrite[ 'slug' ] . '/', '/', $link );
        }

    return $link;

    }

} // class

Thanks, Simon

0

You'll need to add the year, month, and day portions to the post's permalink in your post_link callback:

$link = str_replace(
  '/' . $pto->rewrite[ 'slug' ] . '/',
  '/' . get_the_time( 'Y/m/d', $post ) . '/',
  $link
);

This will return a permalink such as example.com/2014/07/02/post-name.

You'll have to adjust the logic in your pre_get_posts callback so it handles the fact that the year, month, and day query vars will also be present.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.