Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Tusko
Created November 9, 2019 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tusko/738589dd13dbfad2d45b59c76058f554 to your computer and use it in GitHub Desktop.
Save Tusko/738589dd13dbfad2d45b59c76058f554 to your computer and use it in GitHub Desktop.
Remove slug from Custom Post Type in Wordpress
<?php
/*
*** You van use dash-icons https://developer.wordpress.org/resource/dashicons/
*/
add_action( 'init', 'register_cpts' );
function register_cpts() {
register_post_type( 'services',
array(
'labels' => array(
'name' => 'Services',
'singular_name' => 'Services',
'menu_name' => 'Services'
),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'supports' => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
'has_archive' => false,
'rewrite' => true,
'hierarchical' => true,
'show_in_nav_menus' => true,
'capability_type' => 'page',
'query_var' => true,
'menu_icon' => 'dashicons-lock'
) );
register_post_type( 'locations',
array(
'labels' => array(
'name' => 'Locations',
'singular_name' => 'Locations',
'menu_name' => 'Locations'
),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'supports' => array( 'title', 'editor', 'thumbnail' ),
'has_archive' => false,
'rewrite' => true,
'hierarchical' => true,
'show_in_nav_menus' => true,
'capability_type' => 'page',
'query_var' => true,
'menu_icon' => 'dashicons-admin-site-alt3'
) );
if ( defined( 'WP_DEBUG' ) && true !== WP_DEBUG ) {
flush_rewrite_rules();
}
}
add_filter( 'post_type_link', 'sl_custom_post_type_link', 9, 3 );
function sl_custom_post_type_link( $permalink, $post, $leavename ) {
if ( ( ! gettype( $post ) == 'post' ) ) {
return $permalink;
}
switch ( $post->post_type ) {
case 'services':
$permalink = get_home_url() . '/' . $post->post_name;
case 'locations':
$permalink = get_home_url() . '/' . $post->post_name;
break;
}
return $permalink;
}
function sl_cpt_post_names_to_main_query( $query ) {
// Bail if this is not the main query.
if ( ! $query->is_main_query() ) {
return;
}
// Bail if this query doesn't match our very specific rewrite rule.
if ( ! isset( $query->query['page'] ) || 2 !== count( $query->query ) ) {
return;
}
// Bail if we're not querying based on the post name.
if ( empty( $query->query['name'] ) ) {
return;
}
// Add CPT to the list of post types WP will include when it queries based on the post name.
$query->set( 'post_type', array( 'services', 'locations' ) );
}
add_action( 'pre_get_posts', 'sl_cpt_post_names_to_main_query', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment