Skip to content

Instantly share code, notes, and snippets.

@acerus
Created April 19, 2021 16:53
Show Gist options
  • Save acerus/4e2268f05e37cd6918e12eb99d0fe569 to your computer and use it in GitHub Desktop.
Save acerus/4e2268f05e37cd6918e12eb99d0fe569 to your computer and use it in GitHub Desktop.
Create CPT with semantic URL structure (i.e. /taxonomy/term/post)
<?php
/**
* Services class file.
*
* @package WTF
*/
namespace WTF;
/**
* Class Services
*/
class Services {
/**
* Init class.
*/
public function init(): void {
add_filter('init', [$this, 'create_tax']);
add_filter('init', [$this, 'create_cpt']);
add_filter('post_type_link', [$this, 'seo_permalinks'], 10, 2);
add_action('init', [$this, 'rewrite_rules']);
}
public function create_tax() {
register_taxonomy('service_type', ['post', 'services'],
[
'label' => __('Service Types', 'wtf'),
'public' => true,
'show_tagcloud' => false,
'show_in_rest' => true,
'hierarchical' => false,
'show_admin_column' => true,
'query_var' => true
]
);
}
public function create_cpt() {
register_post_type('services',
[
'label' => __('Services', 'wtf'),
'public' => true,
'capability_type' => 'post',
'show_in_rest' => true,
'hierarchical' => false,
'rewrite' => [
'slug' => '/services/%service_types%',
'with_front' => false,
'feeds' => false
],
'query_var' => true,
'supports' => ['title', 'tags', 'editor', 'comments', 'custom-fields', 'thumbnail'],
'has_archive' => 'services',
'taxonomies' => ['service_type', 'post_tag'],
'show_in_nav_menus' => true,
'menu_icon' => 'dashicons-admin-site',
]
);
}
/**
* Adds some rewrite rules for semantic URLs (archive, taxonomy)
*/
public function rewrite_rules() {
add_rewrite_rule(
'services/([a-z]+)/page/?([0-9]{1,})/?$',
'index.php?post_type=services&service_type=$matches[1]&paged=$matches[2]',
'top'
);
add_rewrite_rule(
'services/([a-z]+)/([a-z0-9_-]+)/?$',
'index.php?post_type=services&service_type=$matches[1]&services=$matches[2]',
'top'
);
add_rewrite_rule(
'services/([a-z]+)/?$',
'index.php?post_type=services&service_type=$matches[1]',
'top'
);
add_filter('query_vars', function($vars) {
$vars[] .= 'service_type';
$vars[] .= 'service_type-page';
return $vars;
});
}
/**
* Adding service types to single service URLs: https://wtf.com/services/%service_type%/%service%/
*
* @param $permalink
* @param $post
*
* @return string|string[]
*/
public function seo_permalinks(
$permalink, $post
) {
if (strpos($permalink, '%service_types%') === false) {
return $permalink;
}
$terms = get_the_terms($post, 'service_type');
if ( ! is_wp_error($terms) && ! empty($terms) && is_object($terms[0])) {
$term_slug = array_pop($terms)->slug;
} else {
$term_slug = 'd';
}
return str_replace('%service_types%', $term_slug, $permalink);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment