0

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. can you please tell me how can i show custom posts by category on separate page. Lets say i have CPT “talent” and a category “art”. I have two different posts one is created under CPT “talents” and other is general post created under “posts”. Both posts are assigned to “art” category(this is common for both CPT and general posts). Now i know that for the general posts you can view the category page as domain.com/category/art. For CPT category page i guess the url should be domain.com/talent/art but it is giving me 404 error.
Use http://domain.com/category/art for default/general posts and use http://domain.com/category/art/?post_type=talents for CPT
0

Use built-in categories for custom post types

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.