Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active February 21, 2024 21:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save igorbenic/3ba41de1db69bf028651e98b4615cfee to your computer and use it in GitHub Desktop.
Save igorbenic/3ba41de1db69bf028651e98b4615cfee to your computer and use it in GitHub Desktop.
Taxonomy Rewrite Example
<?php
function rewriting_resources($wp_rewrite) {
$rules = array();
$terms = get_terms( array(
'taxonomy' => 'resource_type',
'hide_empty' => false,
) );
$post_type = 'resources';
foreach ($terms as $term) {
// Is it a child term?
if( $term->parent ) {
$ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
foreach ( (array)$ancestors as $ancestor ) {
$ancestor_term = get_term($ancestor, $taxonomy);
$hierarchical_slugs[] = $ancestor_term->slug;
}
$hierarchical_slugs = array_reverse($hierarchical_slugs);
$hierarchical_slugs[] = $term->slug;
$rules['resources/' . implode('/', $hierarchical_slugs ) . '/([^/]*)$'] = 'index.php?post_type=' . $post_type. '&' . $post_type . '=$matches[1]&name=$matches[1]';
} else {
$rules['resources/' . $term->slug . '/([^/]*)$'] = 'index.php?post_type=' . $post_type. '&' . $post_type . '=$matches[1]&name=$matches[1]';
}
}
// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter('generate_rewrite_rules', 'resources_cpt_generating_rule');
<?php
add_action(‘init’, ‘cpt_resources’);
function cpt_resources() {
$labels = array(
‘name’ => _x(‘Resources’, ‘snt’),
‘singular_name’ => _x(‘Resource’, ‘snt’),
‘add_new’ => _x(‘Add Resource’, ‘snt’),
‘add_new_item’ => __(‘Add Resource’),
‘edit_item’ => __(‘Edit Resource’),
‘new_item’ => __(‘New Resource’),
‘view_item’ => __(‘View Resource’),
‘search_items’ => __(‘Search Resources’),
‘not_found’ => __(‘Nothing found’),
‘not_found_in_trash’ => __(‘Nothing found in Trash’),
‘parent_item_colon’ => ”
);
$args = array(
‘labels’ => $labels,
‘taxonomies’ => array(‘resource_type’),
public’ => true,
‘publicly_queryable’ => true,
‘show_ui’ => true,
‘query_var’ => true,
‘rewrite’ => true,
‘capability_type’ => ‘post’,
‘hierarchical’ => false,
‘menu_position’ => null,
‘supports’ => array(‘title’,’thumbnail’, ‘editor’ ),
);
register_post_type( ‘resources_post_type’ , $args );
}
function resource_type() {
$labels = array(
‘name’ => _x( ‘Resource Types’, ‘Taxonomy General Name’, ‘snt’ ),
‘singular_name’ => _x( ‘Resource Type’, ‘Taxonomy Singular Name’, ‘snt’ ),
‘menu_name’ => __( ‘Resource Types’, ‘snt’ ),
‘all_items’ => __( ‘All Items’, ‘snt’ ),
‘parent_item’ => __( ‘Parent Item’, ‘snt’ ),
‘parent_item_colon’ => __( ‘Parent Item:’, ‘snt’ ),
‘new_item_name’ => __( ‘New Item Name’, ‘snt’ ),
‘add_new_item’ => __( ‘Add New Item’, ‘snt’ ),
‘edit_item’ => __( ‘Edit Item’, ‘snt’ ),
‘update_item’ => __( ‘Update Item’, ‘snt’ ),
‘view_item’ => __( ‘View Item’, ‘snt’ ),
‘separate_items_with_commas’ => __( ‘Separate items with commas’, ‘snt’ ),
‘add_or_remove_items’ => __( ‘Add or remove items’, ‘snt’ ),
‘choose_from_most_used’ => __( ‘Choose from the most used’, ‘snt’ ),
‘popular_items’ => __( ‘Popular Items’, ‘snt’ ),
‘search_items’ => __( ‘Search Items’, ‘snt’ ),
‘not_found’ => __( ‘Not Found’, ‘snt’ ),
‘no_terms’ => __( ‘No items’, ‘snt’ ),
‘items_list’ => __( ‘Items list’, ‘snt’ ),
‘items_list_navigation’ => __( ‘Items list navigation’, ‘snt’ ),
);
$args = array(
‘labels’ => $labels,
‘hierarchical’ => true,
public’ => true,
‘show_ui’ => true,
‘show_admin_column’ => true,
‘show_in_nav_menus’ => true,
‘show_tagcloud’ => true,
‘rewrite’ => array(‘slug’ => ‘resources’)
);
register_taxonomy( ‘resource_type’, array( ‘resources_post_type’ ), $args );
}
add_action( ‘init’, ‘resource_type’, 0 );
function rewriting_resources($wp_rewrite) {
$rules = array();
$terms = get_terms( array(
‘taxonomy’ => ‘resource_type’,
‘hide_empty’ => false,
) );
$post_type = ‘resources_post_type’;
foreach ( $terms as $term ) {
// Is it a child term?
if ( $term->parent ) {
$ancestors = get_ancestors( $term->term_id, $taxonomy, ‘taxonomy’ );
foreach ( (array)$ancestors as $ancestor ) {
$ancestor_term = get_term($ancestor, $taxonomy);
$hierarchical_slugs[] = $ancestor_term->slug;
}
$hierarchical_slugs = array_reverse($hierarchical_slugs);
$hierarchical_slugs[] = $term->slug;
$rules[‘resources/’ . implode(‘/’, $hierarchical_slugs ) . ‘/([^/]*)$’] = ‘index.php?post_type=’ . $post_type. ‘&’ . $post_type . ‘=$matches[1]&name=$matches[1]’;
} else {
$rules[‘resources/’ . $term->slug . ‘/([^/]*)$’] = ‘index.php?post_type=’ . $post_type. ‘&’ . $post_type . ‘=$matches[1]&name=$matches[1]’;
}
}
// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter(‘generate_rewrite_rules’, ‘rewriting_resources’);
function change_link( $permalink, $post ) {
if ( $post->post_type == ‘resources_post_type’ ) {
$resource_terms = get_the_terms( $post, ‘resource_type’ );
$term_slug = ”;
if( ! empty( $resource_terms ) ) {
foreach ( $resource_terms as $term ) {
// The featured resource will have another category which is the main one
if( $term->slug == ‘featured’ ) {
continue;
}
$term_slug = $term->slug;
break;
}
}
$permalink = get_home_url() .”/resources/” . $term_slug . ‘/’ . $post->post_name;
}
return $permalink;
}
add_filter(‘post_type_link’,”change_link”,10,2);
this code in taxonomy-resource_type.php:
queried_object;
$taxonomy->children = get_terms( ‘resource_type’, array( ‘hide_empty’ => 0, ‘parent’ => $taxonomy->term_id, ‘orderby’ => ‘id’, ‘order’ => ‘ASC’, ) );
$parent = $taxonomy->parent;
$not_the_last_subcategory = is_array( $taxonomy->children ) && count( $taxonomy->children ) && $taxonomy->parent == 0;
?>
children);
?>
<div class="pr_subcategorias “>
children as $key=>$subcategory ) {
?>
<a href=">name ?>
<a href="”>
description, false );
echo $description;
?>
<a href=">
children = get_terms( ‘resource_type’, array(‘hide_empty’ => 0, ‘parent’ => $parent, ‘orderby’ => ‘id’, ‘order’ => ‘ASC’, ));
$columnas = count($taxonomy->children);
$current_category = get_query_var(‘resource_type’);
?>
<div class="pr_subcategorias_menu “>
name; ?>
children as $key=>$subcategory ) {
?>
<li class="th_subcategoria slug == $current_category ) echo ‘activo’; ?>><a href="”>name ?>
$current_category,
‘post_type’ => ‘resources_post_type’,
‘posts_per_page’ => -1,
‘orderby’ => ‘menu_order’,
‘order’ => ‘ASC’,
‘no_found_rows’ => true // Si no hay paginacion, hace mas rapido la QUERY
)
);
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) {
$loop->the_post();
$pr_id = get_the_id();
$pr_image = wp_get_attachment_url( get_post_thumbnail_id( $pr_id ) );
?>
<img src=" alt=”” />
<a href="”>
And this in single-resources_post_type.php:
slug;
$current_father = $term[0]->parent;
$taxonomy->children = get_terms( ‘resource_type’, array( ‘hide_empty’ => 0, ‘parent’ => $current_father, ‘orderby’ => ‘id’, ‘order’ => ‘ASC’, ));
$columnas = count($taxonomy->children);
?>
<div class="pr_subcategorias_menu >
children as $key=>$subcategory ) {
?>
<li class="th_subcategoria slug == $current_category ) echo ‘activo’; ?>”><a href=">name ?>
CLIENTE:
SERVICIOS:
AÑO:
PAIS:
<div class="dcha “>
INFO
PROYECTOS RELACIONADOS
PREMIOS
VIDEOS
<?php
if ( get_the_content() ) echo '’ . get_the_content() . ”;
if ( $relaciones ) echo ” . $relaciones . ”;
if ( $premios ) echo ” . $premios . ”;
if ( $videos ) echo ” . $videos . ”;
?>
name . ‘ – ‘ . $current_category; ?>
$current_category,
‘post_type’ => ‘resources_post_type’,
‘post__not_in’ => array( $post_id ),
‘posts_per_page’ => -1,
‘orderby’ => ‘menu_order’,
‘order’ => ‘ASC’,
‘no_found_rows’ => true // Si no hay paginacion, hace mas rapido la QUERY
)
);
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) {
$loop->the_post();
$pr_id = get_the_id();
$pr_image = wp_get_attachment_url( get_post_thumbnail_id( $pr_id ) );
?>
<img src="” alt=”” />
<a href="”>
<?php
// Rewrites rules
add_action( 'generate_rewrite_rules', 'register_proyecto_rewrite_rules' );
function register_proyecto_rewrite_rules( $wp_rewrite ) {
$new_rules = array(
'proyecto/([^/]+)/?$' => 'index.php?proyecto-category=' . $wp_rewrite->preg_index( 1 ),
'proyecto/([^/]+)/([^/]+)/?$' => 'index.php?post_type=proyecto&proyecto-category=' . $wp_rewrite->preg_index( 1 ) . '&proyecto=' . $wp_rewrite->preg_index( 2 ),
'proyecto/([^/]+)/([^/]+)/page/(\d{1,})/?$' => 'index.php?post_type=proyecto&proyecto-category=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 3 ),
'proyecto/([^/]+)/([^/]+)/([^/]+)/?$' => 'index.php?post_type=proyecto&proyecto-category=' . $wp_rewrite->preg_index( 2 ) . '&proyecto=' . $wp_rewrite->preg_index( 3 ),
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
// A hacky way of adding support for flexible custom permalinks
// There is one case in which the rewrite rules from register_kb_rewrite_rules() fail:
// When you visit the archive page for a child section(for example: http://example.com/proyecto/category/child-category)
// The deal is that in this situation, the URL is parsed as a Knowledgebase post with slug “child-category” from the “category” section
function fix_proyecto_subcategory_query($query) {
if ( isset( $query['post_type'] ) && 'proyecto' == $query['post_type'] ) {
if ( isset( $query['proyecto'] ) && $query['proyecto'] && isset( $query['proyecto-category'] ) && $query['proyecto-category'] ) {
$query_old = $query;
// Check if this is a paginated result(like search results)
if ( 'page' == $query['proyecto-category'] ) {
$query['paged'] = $query['name'];
unset( $query['proyecto-category'], $query['name'], $query['proyecto'] );
}
// Make it easier on the DB
$query['fields'] = 'ids';
$query['posts_per_page'] = 1;
// See if we have results or not
$_query = new WP_Query( $query );
if ( ! $_query->posts ) {
$query = array( 'proyecto-category' => $query['proyecto'] );
if ( isset( $query_old['proyecto-category'] ) && 'page' == $query_old['proyecto-category'] ) {
$query['paged'] = $query_old['name'];
}
}
}
}
return $query;
}
add_filter( 'request', 'fix_proyecto_subcategory_query', 10 );
function proyecto_article_permalink( $article_id, $section_id = false, $leavename = false, $only_permalink = false ) {
$taxonomy = 'proyecto-category';
$article = get_post( $article_id );
$return = 'post_type%' : $article->post_name ) );
$return .= $permalink . '/” >' . get_the_title( $article->ID ) . '';
return ( $only_permalink ) ? $permalink : $return;
}
function filter_proyecto_post_link( $permalink, $post, $leavename ) {
if ( get_post_type( $post->ID ) == 'proyecto' ) {
$terms = wp_get_post_terms( $post->ID, 'proyecto-category' );
$term = ( $terms ) ? $terms[0]->term_id : false;
$permalink = proyecto_article_permalink( $post->ID, $term, $leavename, true );
}
return $permalink;
}
add_filter( 'post_type_link', 'filter_proyecto_post_link', 100, 3 );
function filter_proyecto_section_terms_link( $termlink, $term, $taxonomy = false ) {
if ( $taxonomy == 'proyecto-category' ) {
$section_ancestors = get_ancestors( $term->term_id, $taxonomy );
krsort( $section_ancestors );
$termlink = home_url( '/proyecto/' );
foreach ( $section_ancestors as $ancestor ) {
$section_ancestor = get_term( $ancestor, $taxonomy );
$termlink .= $section_ancestor->slug . '/';
}
$termlink .= trailingslashit( $term->slug );
}
return $termlink;
}
add_filter( 'term_link', 'filter_proyecto_section_terms_link', 100, 3 );
add_action( 'template_redirect', 'my_fancy_template_redirect' );
function my_fancy_template_redirect(){
global $wp_query;
// Check if we are querying proyecto-posts:
if ( $wp_query->query_vars['post_type'] == 'proyecto' ) {
// Then check if we are dealing with a single proyecto post or just multiple proyecto posts:
if ( is_single() ) {
locate_template( array( 'templates/proyecto-single.php' ), true );
die();
}
}
}
<?php
function rewriting_resources($wp_rewrite) {
$rules = array();
$terms = get_terms( array(
'taxonomy' => 'resource_type',
'hide_empty' => false,
) );
$post_type = 'resources_cpt';
foreach ($terms as $term) {
// Is it a child term?
if( $term->parent ) {
$ancestors = get_ancestors( $term->term_id, $term->taxonomy, 'taxonomy' );
foreach ( (array)$ancestors as $ancestor ) {
$ancestor_term = get_term($ancestor, $term->taxonomy);
$hierarchical_slugs[] = $ancestor_term->slug;
}
$hierarchical_slugs = array_reverse($hierarchical_slugs);
$hierarchical_slugs[] = $term->slug;
$rules['resources/' . implode('/', $hierarchical_slugs ) . '/([^/]*)$'] = 'index.php?post_type=' . $post_type. '&' . $post_type . '=$matches[1]&name=$matches[1]';
} else {
$rules['resources/' . $term->slug . '/([^/]*)$'] = 'index.php?post_type=' . $post_type. '&' . $post_type . '=$matches[1]&name=$matches[1]';
}
}
// merge with global rules
$wp_rewrite->rules = $rules + $wp_rewrite->rules;
}
add_filter('generate_rewrite_rules', 'rewriting_resources');
@locke85
Copy link

locke85 commented Dec 1, 2022

`<?php

if ( ! function_exists('wg_seo_chat') ) {
// Register Custom Post Type
function wg_seo_chat() {
$labels = array(
'name' => _x( 'Chats', 'Post Type General Name', 'wg_seo_chat' ),
'singular_name' => _x( 'Chat', 'Post Type Singular Name', 'wg_seo_chat' ),
'menu_name' => __( 'Chat', 'wg_seo_chat' ),
'name_admin_bar' => __( 'Chat', 'wg_seo_chat' ),
'archives' => __( 'Chat Archives', 'wg_seo_chat' ),
'attributes' => __( 'Chat Attributes', 'wg_seo_chat' ),
'parent_item_colon' => __( 'Parent Chat:', 'wg_seo_chat' ),
'all_items' => __( 'All Chats', 'wg_seo_chat' ),
'add_new_item' => __( 'Add New Chat', 'wg_seo_chat' ),
'add_new' => __( 'Add New', 'wg_seo_chat' ),
'new_item' => __( 'New Chat', 'wg_seo_chat' ),
'edit_item' => __( 'Edit Chat', 'wg_seo_chat' ),
'update_item' => __( 'Update Chat', 'wg_seo_chat' ),
'view_item' => __( 'View Chat', 'wg_seo_chat' ),
'view_items' => __( 'View Chats', 'wg_seo_chat' ),
'search_items' => __( 'Search Chat', 'wg_seo_chat' ),
'not_found' => __( 'Not found', 'wg_seo_chat' ),
'not_found_in_trash' => __( 'Not found in Trash', 'wg_seo_chat' ),
'featured_image' => __( 'Featured Image', 'wg_seo_chat' ),
'set_featured_image' => __( 'Set featured image', 'wg_seo_chat' ),
'remove_featured_image' => __( 'Remove featured image', 'wg_seo_chat' ),
'use_featured_image' => __( 'Use as featured image', 'wg_seo_chat' ),
'insert_into_item' => __( 'Insert into Chat', 'wg_seo_chat' ),
'uploaded_to_this_item' => __( 'Uploaded to this Chat', 'wg_seo_chat' ),
'items_list' => __( 'Chat list', 'wg_seo_chat' ),
'items_list_navigation' => __( 'Chat list navigation', 'wg_seo_chat' ),
'filter_items_list' => __( 'Filter Chat list', 'wg_seo_chat' ),
);
$rewrite = array(
'slug' => 'hilfe-chats',
'with_front' => true,
'pages' => true,
'feeds' => true,

	);
	$args = array(
		'label'                 => __( 'Chat', 'wg_seo_chat' ),
		'taxonomies' 			=> array('wg_chat_category'),
		'description'           => __( 'Shares answers for user questions about SEO', 'wg_seo_chat' ),
		'labels'                => $labels,
		'supports'              => array( 'title', 'editor', 'thumbnail', 'comments', 'revisions', 'custom-fields', 'page-attributes', 'post-formats', 'excerpt' ),
		'hierarchical'          => true,
		'public'                => true,
		'show_ui'               => true,
		'show_in_menu'          => true,
		'menu_position'         => 5,
		'menu_icon'             => 'dashicons-format-chat',
		'show_in_admin_bar'     => true,
		'show_in_nav_menus'     => true,
		'show_in_rest'          => true,
		'can_export'            => true,
		'has_archive'           => true,
		'exclude_from_search'   => false,
		'publicly_queryable'    => true,
		'rewrite'               => $rewrite,
		'capability_type'       => 'page',
	);
	register_post_type( 'wg_seo_chat', $args );
}
add_action( 'init', 'wg_seo_chat', 0 );
}


if ( ! function_exists( 'wg_chat_category' ) ) {
	// Register Custom Taxonomy
	function wg_chat_category() {
	$labels = array(
			'name'                       => _x( 'Chat Categories', 'Taxonomy General Name', 'wg_chat_category' ),
			'singular_name'              => _x( 'Chat Category', 'Taxonomy Singular Name', 'wg_chat_category' ),
			'menu_name'                  => __( 'Chat Category', 'wg_chat_category' ),
			'all_items'                  => __( 'All Chat Categories', 'wg_chat_category' ),
			'parent_item'                => __( 'Parent Chat Category', 'wg_chat_category' ),
			'parent_item_colon'          => __( 'Parent Chat Category:', 'wg_chat_category' ),
			'new_item_name'              => __( 'New Chat Category Name', 'wg_chat_category' ),
			'add_new_item'               => __( 'Add New Chat Category', 'wg_chat_category' ),
			'edit_item'                  => __( 'Edit Chat Category', 'wg_chat_category' ),
			'update_item'                => __( 'Update Chat Category', 'wg_chat_category' ),
			'view_item'                  => __( 'View Chat Category', 'wg_chat_category' ),
			'separate_items_with_commas' => __( 'Separate Chat Categories with commas', 'wg_chat_category' ),
			'add_or_remove_items'        => __( 'Add or remove Chat Categories', 'wg_chat_category' ),
			'choose_from_most_used'      => __( 'Choose from the most used', 'wg_chat_category' ),
			'popular_items'              => __( 'Popular Chat Categories', 'wg_chat_category' ),
			'search_items'               => __( 'Search Chat Category', 'wg_chat_category' ),
			'not_found'                  => __( 'Not Found', 'wg_chat_category' ),
			'no_terms'                   => __( 'No Chat Categories', 'wg_chat_category' ),
			'items_list'                 => __( 'Chat Category list', 'wg_chat_category' ),
			'items_list_navigation'      => __( 'Chat Category list navigation', 'wg_chat_category' ),
		);
		$args = array(
			'labels'                     => $labels,
			'hierarchical'               => true,
			'public'                     => true,
			'show_ui'                    => true,
			'show_admin_column'          => true,
			'show_in_nav_menus'          => true,
			'show_in_rest'               => true,
			'show_tagcloud'              => true,
			'rewrite'                    => array('slug' => 'hilfe-chat')
		);
		register_taxonomy( 'wg_chat_category', array( 'wg_seo_chat' ), $args );
	}
	add_action( 'init', 'wg_chat_category', 0 );
	}

	/** Rewrite rule to handle third level slug */

	function chat_cpt_generating_rule($wp_rewrite) {
		$rules = array();
		$terms = get_terms( array(
			'taxonomy' => 'wg_chat_category',
			'hide_empty' => false,
		) );
	   
		$post_type = 'wg_seo_chat';
	
		foreach ($terms as $term) {    
					
			$rules['hilfe-chat/' . $term->slug . '/([^/]*)$'] = 'index.php?post_type=' . $post_type. '&wg_seo_chat=$matches[1]&name=$matches[1]';
							
		}
	
		// merge with global rules
		$wp_rewrite->rules = $rules + $wp_rewrite->rules;
	}
	add_filter('generate_rewrite_rules', 'chat_cpt_generating_rule');

	/** Inject the chat category into the CPT Link */

	function change_link( $permalink, $post ) {

		if( $post->post_type == 'wg_seo_chat' ) {
			$chat_terms = get_the_terms( $post, 'wg_chat_category' );
			$term_slug = '';
			if( ! empty( $chat_terms ) ) {
				foreach ( $chat_terms as $term ) {
	
					// The featured chat will have another category which is the main one
					if( $term->slug == 'featured' ) {
						continue;
					}
	
					$term_slug = $term->slug;
					break;
				}
			}
			$permalink = get_home_url() ."/hilfe-chat/" . $term_slug . '/' . $post->post_name;
		}
		return $permalink;
	
	}
	add_filter('post_type_link',"change_link",10,2);`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment