1

I've seen several posts lately with people easily removing the slugs from a single custom post type via the following function:

function hf_remove_slug( $post_link, $post, $leavename ) {

    if(('pop-tags' == $post->post_type || 'furniture-type' == $post->post_type) && 'publish' == $post->post_status) {
        return $post_link;
    }

    $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link 
);

   return $post_link;
}
add_filter( 'post_type_link', 'hf_remove_slug', 10, 3 );

function hf_parse_request( $query ) {

    if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
        return;
    }

    if ( ! empty( $query->query['name'] ) ) {
        $query->set( 'post_type', array( 'post', 'pop-tags', 'furniture-type', 'page' ) );
    }
}
add_action( 'pre_get_posts', 'hf_parse_request' );

However I've been unable to get this to work when I add in multiple custom post types. Can anyone help with this/explain?

  • Could just be a typo on WPSE but you're missing a quote mark after 'custom_post_type2. You might also try reformatting the remove_cpt_slug function as a positive match: if(('custom_post_type1' == $post->post_type || 'custom_post_type2' == $post->post_type) && 'publish' == $post->post_status) do your str_replace and return. – WebElaine May 12 '17 at 15:39
  • Thanks @WebElaine - a good thought, unfortunately it doesn't seem to be working either (neither post types seem to get their slug removed). I also did check my quotes, I just forgot to include on in my initial question - I've update my functions in the question to match what I've tried. – Laurel May 12 '17 at 16:21
  • 1
    If you're testing for the opposite case, then you need to reverse what it's doing when it passes that test- you want to replace the link when it passes, not return the link unaltered. – Milo May 12 '17 at 18:28
1

Looks like you have your if doing the opposite of what you want. You're returning the unaltered link if you're on 'furniture-type' or 'pop-tags'.

This should work:

function hf_remove_slug( $post_link, $post, $leavename ) {

    if(('pop-tags' == $post->post_type || 'furniture-type' == $post->post_type) && 'publish' == $post->post_status) {
        $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link);
        return $post_link;
    }

   return $post_link;
}

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.