Forum Replies Created

Viewing 3 replies - 1 through 3 (of 3 total)
  • All GFC comments display wordpress’s anonymous avatar. What happened?

    Just noticed that %post_id% overlaps with the built-in permalink placeholders, so your normal post permalinks might be corrupted if you are using post id’s there as well. Simply change %post_id% to something original like %cpt_id% throughout your own functions and you’ll be fine.

    I was having the same problem as well: couldn’t find a way to use post ID in the permalink of my custom post type. Here’s what I did.

    Add the rewrite rule:

    add_action('init', 'myposttype_rewrite');
    function myposttype_rewrite() {
    	global $wp_rewrite;
    	$queryarg = 'post_type=myposttype&p=';
    	$wp_rewrite->add_rewrite_tag('%post_id%', '([^/]+)', $queryarg);
    	$wp_rewrite->add_permastruct('myposttype', '/myposttype/%post_id%', false);
    	}

    And hook the post_type_link filter:

    add_filter('post_type_link', 'myposttype_permalink', 1, 3);
    function myposttype_permalink($post_link, $id = 0, $leavename, $sample) {
    	global $wp_rewrite;
    	$post = &get_post($id);
    	if ( is_wp_error( $post ) )
    		return $post;
    	$newlink = $wp_rewrite->get_extra_permastruct('myposttype');
    	$newlink = str_replace("%post_id%", $post->ID, $newlink);
    	$newlink = home_url(user_trailingslashit($newlink));
    	return $newlink;
    	}

    Remember to flush your rewrite rules before you view your custom post type using the new permalink. Simply visit your Permalink settings page in the admin panel.

    I still recommend WordPress – in the future versions – to have better UI for creating/managing custom post types, and allow a more flexible way of configuring custom post type permalinks.

Viewing 3 replies - 1 through 3 (of 3 total)