Skip to content

Instantly share code, notes, and snippets.

@hawkidoki
Created October 21, 2019 07:10
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 hawkidoki/64f14c9ebb53eec7656048e3e2f2522a to your computer and use it in GitHub Desktop.
Save hawkidoki/64f14c9ebb53eec7656048e3e2f2522a to your computer and use it in GitHub Desktop.
<?php
add_filter('request', 'hwk_post_type_toplevel_request', 1, 1);
function hwk_post_type_toplevel_request($query){
$post_type = 'portfolio';
if(isset($query[$post_type]) && isset($query['post_type']) && $query['post_type'] === 'portfolio')
return $query;
$name = false;
// Found children
if(isset($query['attachment'])){
$include_children = true;
$name = $query['attachment'];
}
// Default: no children
elseif(isset($query['name'])){
$include_children = false;
$name = $query['name'];
}
if(!$name)
return $query;
$get_posts = get_posts(array(
'name' => $name,
'post_type' => $post_type,
'posts_per_page' => 1
));
if(empty($get_posts))
return $query;
$post = $get_posts[0];
if($include_children){
unset($query['attachment']);
$parent = $post->post_parent;
while($parent){
$parent_post = get_post($parent);
$name = $parent_post->post_name . '/' . $name;
$parent = $parent_post->post_parent;
}
}else{
unset($query['name']);
}
$query['post_type'] = $post_type;
$query[$post_type] = $name;
return $query;
}
add_action('init', 'hwk_post_type_toplevel_add_rewrite_rule');
function hwk_post_type_toplevel_add_rewrite_rule(){
add_rewrite_rule(
'(.?.+?)?(:/([0-9]+))?/?$',
'index.php?portfolio=$matches[1]&post_type=portfolio&page=$matches[2]',
'bottom'
);
}
add_filter('post_type_link', 'hwk_post_type_toplevel_permalink', 10, 2);
function hwk_post_type_toplevel_add_rewrite_rule($post_link, $post, $leavename){
if('portfolio' != $post->post_type !== 'portfolio' || $post->post_status !== 'publish')
return $post_link;
$post_link = str_replace('/' . $post->post_type . '/', '/', $post_link);
return $post_link;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment