Custom Permalink with Dynamic Taxonomy for Custom Post Type – Works, but breaks other permalinks

My custom permalink with dynamic taxonomy is working for my custom post type. However, it breaks all my other permalinks. They display a 404 error in the content area (header and sidebar still display).

I used the following code to create the dynamic permalinks for the custom post type:

/*Adds Custom Permalinks for Course Segments*/
function custom_post_link($post_link, $id = 0)
{
  $post = get_post($id);

  if(!is_object($post) || $post->post_type != 'course-segment')
  {
    return $post_link;
  }
  $course="course-segment";

  if($terms = wp_get_object_terms($post->ID, 'course'))
  {
    $course = $terms[0]->slug;
  }
  return str_replace('%course%', $course, $post_link);

  return $post_link;
}

add_filter('post_type_link', 'custom_post_link', 1, 3);

I also added the following to my create_post_type() function:

'rewrite' => array('slug' => '%course%')

I got the code to do this from: https://stackoverflow.com/questions/7723457/wordpress-custom-type-permalink-containing-taxonomy-slug.

By simply commenting out the following two lines of code my old permalinks work, but of course my dynamic permalinks don’t:

//add_filter('post_type_link', 'custom_post_link', 1, 3);


//'rewrite' => array('slug' => '%course%')

In Settings my permalinks are set to %postname%.

Any thoughts or insights on how I can get both my normal permalinks and my dynamic custom post type permalinks working would be most appreciated! -Mark

2 Answers
2

If you’re running WordPress 3.0.1 or later, I believe your problem lies with the ‘post_type_link’ filter declaration and function arguments.

When the ‘post_type_link’ filter is applied, it passes the following 4 arguments:

apply_filters('post_type_link', $post_link, $post, $leavename, $sample);

But your function accepts $post_link and $id.

Try the following adjustments:

function custom_post_link( $post_link, $post ) {

    if ( $post->post_type != 'course-segment')
        return $post_link;

    $course="course-segment";
    if( $terms = wp_get_object_terms( $post->ID, 'course' ) )
        $course = $terms[0]->slug;

    return str_replace( '%course%', $course, $post_link );

}
add_filter( 'post_type_link', 'custom_post_link', 1, 2 );

Leave a Comment