Although this is my first post but i have been coming here for answers so I know the rule and this isn’t a duplicate because i have tried whatever i could but couldn’t seem to get my codes to work. Note that I have gone through many answers and tried out several ways but none worked.
Here is the problem, I am trying to rewrite the permalink structure, I wanted to add both the category and parent category to the url so it looks like the example below but somehow my code doesn’t seem to work, the category and the parent slug are missing on the url from the function below.
Function 1 – This one works ok, just for your info
function custom_list_rewrite() {
global $wp_rewrite;
$query_arg = 'post_type=custom_list&p=';
$wp_rewrite->add_rewrite_tag( '%post_id%', '([^/]+)', $query_arg );
$wp_rewrite->add_permastruct( 'custom_list', '%post_id%-%category%', false );
}
add_action( 'init', 'custom_list_rewrite' );
Function 2 –
function custom_permalink( $post_link, $id = 0, $leavename ) {
global $wp_rewrite;
$post = &get_post( $id );
if ( is_wp_error( $post ) || $post->post_type != 'custom_list' )
return $post_link;
//first thing first, get the category id from post id
$category_id = get_the_category( $post->ID );
//firstly, load data for your child category
$child = get_category( $category_id );
//from your child category, grab parent ID
$parent = $child->parent;
//load object for parent category
$parent_name = get_category( $parent );
//grab a category name
$parent_name = $parent_name->name;
$newlink = $wp_rewrite->get_extra_permastruct( 'custom_list' );
$newlink = str_replace( '%post_id%', $post->ID, $newlink );
$newlink = str_replace( '%category%', $parent_name.'-'.$child->name, $newlink );
$newlink = home_url( $newlink );
return $newlink;
}
add_filter( 'post_type_link', 'custom_permalink', 1, 3 );
In the perfect world my link should look like http://www.mydomain.com/123-honda-civic
but honda-civic is missing, so it’s showing http://www.mydomain.com/123-
Please point me to the right direction.
thanks.