Piyush
Piyush

Reputation: 74

Use built-in categories for custom post types

Can we use built-in categories for the custom post types. and how can I access the category page(url) for new custom post types.

Upvotes: 0

Views: 233

Answers (3)

Piyush
Piyush

Reputation: 74

The real solution is to setup CTP slug to "slug/%category%"

Then updating the CPT permalink (put following code in functions.php)

add_filter('post_link', 'category_permalink', 1, 3);
add_filter('post_type_link', 'category_permalink', 1, 3);


function category_permalink($permalink, $post_id, $leavename) {
    //con %category% catturo il rewrite del Custom Post Type
    if (strpos($permalink, '%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, 'category');
        if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0]))
            $taxonomy_slug = $terms[0]->slug;
        else $taxonomy_slug = 'no-category';

    return str_replace('%category%', $taxonomy_slug, $permalink);
}

On the top of category.php, add a check

$segments = explode('/', trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'));
//print_r($segments);
if($segments[1] == 'CPT Slug'){ //Change CPT Slug to your own slug
//Show CPT posts
}else{
//General posts
}

Upvotes: 0

user3201528
user3201528

Reputation:

Use built-in categories for custom post types

Upvotes: 0

amit
amit

Reputation: 874

Yes you can add built in categories to custom post type.

Just add below code into functions.php file

add_action( 'init', 'add_category_taxonomy_to_custom_post' );
function add_category_taxonomy_to_custom_post() {
    register_taxonomy_for_object_type( 'category', 'custom_post' );
}

where custom_post is the Post Type Key.

Upvotes: 2

Related Questions