John Davidson

php - Category and subcategory in url Custom post types

0 comments
Message:


I added cpt and custom taxonomy. I writed function in my functions.php which adding in my url, category and subcategory then my url is "mysite.com/house/category/subcategory/post_name". Url show but not working, because show message "page not found". If I delete category in my url or subcategory this single page showing. Please help me! My code:


add_filter('post_type_link', 'projectcategory_permalink_structure', 10, 4);
function projectcategory_permalink_structure($post_link, $post, $leavename, $sample) {
if (false !== strpos($post_link, '%kategorie_dladomu%')) {
$terms = get_the_terms($post->ID, 'kategorie_dladomu');

foreach ( $terms as $term ) {
if ( $terms->parent == 0 ){
$category = $term->slug;
foreach( $terms as $subterms ){
if ( $subterms->parent == $term->term_id ){
$subcategory = $subterms->slug;
}
}
}
}
$slug = "$category/$subcategory";
if ( ! empty( $slug ) ) {
return str_replace( '%kategorie_dladomu%' , $slug , $post_link );
}
}
return $post_link;
}


My Answer:
It looks like there might be a small issue in your code. In the line where you are checking for the parent term, you are using `$terms->parent` instead of `$term->parent` and `$terms->term_id` instead of `$term->term_id`.

Here is the corrected code:

php
add_filter('post_type_link', 'projectcategory_permalink_structure', 10, 4);
function projectcategory_permalink_structure($post_link, $post, $leavename, $sample) {
if (false !== strpos($post_link, '%kategorie_dladomu%')) {
$terms = get_the_terms($post->ID, 'kategorie_dladomu');

foreach ( $terms as $term ) {
if ( $term->parent == 0 ){
$category = $term->slug;
foreach( $terms as $subterms ){
if ( $subterms->parent == $term->term_id ){
$subcategory = $subterms->slug;
}
}
}
}
$slug = "$category/$subcategory";
if ( ! empty( $slug ) ) {
return str_replace( '%kategorie_dladomu%' , $slug , $post_link );
}
}
return $post_link;
}


Please try this corrected code and see if it resolves the issue with the URLs not working. Let me know if you need any further assistance.

Rate this post

3 of 5 based on 8693 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us