Support » Requests and Feedback » (Fix Included) Support Date Permalinks With Custom Post Types

  • One weakness in the new custom post type feature is the inability to support custom permalink structures. I modified the file wp-includes/link-template.php to support it, and it’d be great to see this get into a future release.

    Right now, when setting a custom permalink structure for a custom post type (using add_permastruct()), if the structure contains date tags like %year% it is broken. Routing tables (in $wp_rewrite) are set properly, but the permalinks returned by get_permalink() are busted.

    This code fixes that problem to support the permalink tags %year%, %monthnum%, %day%, %hour%, %minute%, and %second%. Now all of those tags can be used in the permastructs for custom post types.

    To use them you need to call:
    add_permastruct('<post-type>', "<permastruct>", true, EP_NONE);
    after you call register_post_type, using %<post-type>% for the post’s slug. (For example, the permastruct for my custom ‘news’ type is ‘news/%year%/%monthnum%/%news%’)

    Here’s the code with my addition commented out:

    function get_post_permalink( $id = 0, $leavename = false, $sample = false ) {
    	global $wp_rewrite;
    	$post = &get_post($id);
    	if ( is_wp_error( $post ) )
    		return $post;
    	$post_link = $wp_rewrite->get_extra_permastruct($post->post_type);
    	$slug = $post->post_name;
    	$draft_or_pending = in_array( $post->post_status, array( 'draft', 'pending', 'auto-draft' ) );
    	$post_type = get_post_type_object($post->post_type);
    	if ( !empty($post_link) && ( ( isset($post->post_status) && !$draft_or_pending ) || $sample ) ) {
    		if ( ! $leavename ) {
    			if ( $post_type->hierarchical )
    				$slug = get_page_uri($id);
    			$post_link = str_replace("%$post->post_type%", $slug, $post_link);
    		$post_link = home_url( user_trailingslashit($post_link) );
    	} else {
    		if ( $post_type->query_var && ( isset($post->post_status) && !$draft_or_pending ) )
    			$post_link = add_query_arg($post_type->query_var, $slug, '');
    			$post_link = add_query_arg(array('post_type' => $post->post_type, 'p' => $post->ID), '');
    		$post_link = home_url($post_link);
    	/******** Support more permalink structures (Richard Connamacher) ********/
    	$rewritecode = array(
    	$unixtime = strtotime($post->post_date);
    	$date = explode(" ",date('Y m d H i s', $unixtime));
    	$rewritereplace = array(
    	$post_link = str_replace($rewritecode, $rewritereplace, $post_link);
    	/******** End addition ********/
    	return apply_filters('post_type_link', $post_link, $post, $leavename, $sample);
  • The topic ‘(Fix Included) Support Date Permalinks With Custom Post Types’ is closed to new replies.