0

I have created a custom post type plugin that when the user assigns the post to a taxonomy (termed 'classification' in the site), it is added to the url slug.

So basically it renders: site.com/data/{classification}/{page-title}

However, I'm not sure how to remove the taxonomy (classification) from the slug when the user does not select one. My code is below:

function classification_permalink($permalink, $post_id, $leavename) {
    if (strpos($permalink, '%classification%') === FALSE) return $permalink;
        // Get post
        $post = get_post($post_id);
        if (!$post) return $permalink;

        // Get taxonomy terms
        $terms = wp_get_object_terms($post->ID, 'classification');
        if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0]))
            $taxonomy_slug = $terms[0]->slug;
        else $taxonomy_slug = 'no-classification';

    return str_replace('%classification%', $taxonomy_slug, $permalink);

Obviously the else $taxonomy_slug = 'no-classification'; is what the slug defaults to when a taxonomy is not chosen.

But how would I edit that line so the slug, when no taxonomy is assigned, would revert to the root so it would read: site.com/data/{page-title} ?

The full plugin is on my github: https://github.com/tgelles/dr12-post-types

0

The post_type_link filter is responsible for modifying the permalinks that are output, but it's not connected to resolving incoming requests for those permalinks. So you'll need to modify your function to output the correct links, but also add a rewrite rule so WordPress knows what to do when those pages are requested.

This is all untested, but off the top of my head you could modify the classification slug to add a trailing slash:

$taxonomy_slug = $terms[0]->slug . '/';

then modify the no classification case to just be an empty string:

else $taxonomy_slug = '';

Then replace the classification tag and trailing slash:

return str_replace('%classification%/', $taxonomy_slug, $permalink);

Then to handle those requests without classification, add another rewrite rule on init:

add_rewrite_rule(
    'data/([^/]+)/?$',
    'index.php?dr12-documentation=$matches[1]',
    'top'
);
  • This works perfectly, thanks! I found I didn't need to add the additional rewrite rule; but in the future where exactly would that code go? Would it be right after line 107? – timmyg Jun 26 '14 at 14:23

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.