Skip to content

Instantly share code, notes, and snippets.

@chrisjangl
Last active July 10, 2020 20:00
Show Gist options
  • Save chrisjangl/46a099cdd1c6eb9f1c7241c3ca1f5734 to your computer and use it in GitHub Desktop.
Save chrisjangl/46a099cdd1c6eb9f1c7241c3ca1f5734 to your computer and use it in GitHub Desktop.
removes the slug from a custom post type
/**
* credit to: https://wordpress.stackexchange.com/q/291735
*
*/
/**
* remove the slug from published gallery permalinks.
*
* Makes sure to only touch our CPT
*
*/
function we_remove_gallery_cpt_slug( $post_link, $post ) {
// check that we're only working with gallery-new posts, and that they're published
if ( 'gallery-new' === $post->post_type && 'publish' === $post->post_status ) {
// replace
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
}
return $post_link;
}
add_filter( 'post_type_link', 'we_remove_gallery_cpt_slug', 10, 2 );
function we_add_gallery_cpt_posts_to_main_query( $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', 'gallery-new', 'page' ) );
} elseif ( ! empty( $query->query['pagename'] ) && false === strpos( $query->query['pagename'], '/' ) ) {
$query->set( 'post_type', array( 'post', 'gallery-new', 'page' ) );
// We also need to set the name query var since redirect_guess_404_permalink() relies on it.
$query->set( 'name', $query->query['pagename'] );
}
}
add_action( 'pre_get_posts', 'we_add_gallery_cpt_posts_to_main_query');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment