Last active
August 30, 2019 03:48
-
-
Save frensuren/b99db1a8eb0362ff7b299d57c366c51e to your computer and use it in GitHub Desktop.
Code to register custom posttype and custom taxonomy with custom permalink structure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Custom Post Types */ | |
function theme_post_types(){ | |
register_post_type('product', array( | |
'labels' => array( | |
'name' => __('Products'), | |
'singular_name' => __('Product'), | |
'menu_name' => __('Products'), | |
'add_new_item' => __('Add New Product'), | |
'edit_item' => __('Edit Product'), | |
'new_item' => __('Add New Product') | |
), | |
'public' => true, | |
'has_archive' => false, | |
'_builtin' => false, | |
'rewrite' => array("slug" => "product","with_front'=>false"), | |
'supports' => array('title', 'editor', 'thumbnail', 'excerpt' ), | |
'taxonomies' => array('post_tag'), | |
'rewrite' => array('slug' => 'product/%product-category%','with_front'=>false) | |
) | |
); | |
} | |
/* Custom Taxonomies */ | |
function theme_taxonomies(){ | |
register_taxonomy( | |
'product-category', | |
array( | |
'product' | |
), | |
array( | |
'hierarchical' => true, | |
'label' => 'Product Categories', | |
'query_var' => true, | |
'public' => true, | |
'rewrite' => array( | |
'hierarchical' => true | |
) | |
) | |
); | |
} | |
add_filter('post_link', 'product_permalink', 1, 3); | |
add_filter('post_type_link', 'product_permalink', 1, 3); | |
function product_permalink($permalink, $post_id, $leavename) { | |
if (strpos($permalink, '%product-category%') === FALSE) return $permalink; | |
// Get post | |
$post = get_post($post_id); | |
if (!$post) return $permalink; | |
// Get taxonomy terms | |
$terms = wp_get_object_terms($post->ID, 'product-category'); | |
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) | |
$taxonomy_slug = $terms[0]->slug; | |
else $taxonomy_slug = 'uncategorized'; | |
return str_replace('%product-category%', $taxonomy_slug, $permalink); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment