0

I'm trying to add specific categories to a CPT and that only when adding a new post you would be able to see the categories that are associated with those post type.

Also, I want to be able to add categories from the backend and not from the code as I have lots of categories that will be changing.

If there is a plugin that does it it's great but I'm also looking to understand how it's done. Thanks a lot

0

Here is my code, which I have created in one of my project. Where, you have supposed to be register your CPT name as "products". So, the created taxonomy visible to your CPT products only. Add these codes in your functions.php file. It's simple no need of plugin.

/* Link products CPT to categories taxonomy
*/
add_action( 'init', 'add_category_taxonomy_to_products' );
function add_category_taxonomy_to_products() {
    register_taxonomy_for_object_type( 'category', 'products' ); // CPT as products
}

//Adding taxonomies for custom post type products
function create_products_taxonomies() {
    $labels = array(
        'name'              => _x( 'Products Categories', 'taxonomy general name' ),
        'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
        'search_items'      => __( 'Search Categories' ),
        'all_items'         => __( 'All Categories' ),
        'parent_item'       => __( 'Parent Category' ),
        'parent_item_colon' => __( 'Parent Category:' ),
        'edit_item'         => __( 'Edit Category' ),
        'update_item'       => __( 'Update Category' ),
        'add_new_item'      => __( 'Add New Category' ),
        'new_item_name'     => __( 'New Category Name' ),
        'menu_name'         => __( 'Categories' ),
    );

    $args = array(
        'hierarchical'      => true, // Set this to 'false' for non-hierarchical taxonomy (like tags)
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array( 'slug' => 'categories' ),
    );

    register_taxonomy( 'products_categories', array( 'products' ), $args );
    flush_rewrite_rules() ;
}
add_action( 'init', 'create_products_taxonomies', 0 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.