Aurangajeb

Remove CPT name from slug and query request

Jan 11th, 2022
904
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.86 KB | None | 0 0
  1. /**
  2. * Step 1:
  3. * Change CPT slug name from the slug/permalink
  4. **/
  5. function remove_cptname_from_slug( $post_link, $post, $leavename ) {
  6.  
  7.     if ( 'docs' != $post->post_type || 'publish' != $post->post_status ) {
  8.         return $post_link;
  9.     }
  10.  
  11.     $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
  12.  
  13.     return $post_link;
  14. }
  15. add_filter( 'post_type_link', 'remove_cptname_from_slug', 10, 3 );
  16.  
  17. /**
  18. * Step 2:
  19. * Change CPT slug name from query request
  20. **/
  21. function parse_cptname_on_query_request( $query ) {
  22.  
  23.     if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
  24.         return;
  25.     }
  26.  
  27.     if ( ! empty( $query->query['name'] ) ) {
  28.         $query->set( 'post_type', array( 'post', 'docs', 'page' ) );
  29.     }
  30. }
  31. add_action( 'pre_get_posts', 'parse_cptname_on_query_request' );
Advertisement
Add Comment
Please, Sign In to add comment