How to create categories for a Post type in Wordpress?

Asked

Viewed 1,443 times

1

Simple doubt, but I can’t find a solution. I created a type of Post called "Products" in functions.php, but it doesn’t come with categories natively. What do I put in the functions to allow the user to give a category for a Product? I got it with the code:

Function demo_add_default_boxes() { register_taxonomy_for_object_type('Category', 'product'); register_taxonomy_for_object_type('post_tag', 'product'); }

But the categories are shared with the main posts and the type of Post Product. How to make to have different categories for each type of Post?

1 answer

2


You can achieve your goal by registering a custom taxonomy for your Custom Post as follows (I will assume that the post type is called product, and that taxonomy is called product type):

/* Action para o registro da Custom Taxonomy Tipo de Produto */
add_action( 'init', 'create_custom_tax_tipo' );

/* Método para o registro da Custom Taxonomy Tipo de Produto */ 
function create_custom_tax_tipo(){
    $custom_tax_nome = 'tipo_de_produto';
    $custom_post_type_nome = 'produto';
    $args = array(
        'label' => __('Tipo de Produto'),
        'hierarchical' => true,
        'rewrite' => array('slug' => 'tipo')
    );
    register_taxonomy( $custom_tax_nome, $custom_post_type_nome, $args );
}

Put this code in your plugin files or in your functions.php. Stay tuned for the way you baptize your Custom Posts and Custom Taxonomies. The use of words like Category (which should be a reserved word in WP) can be harmful.

More about the method register_taxonomy() on Codex.

If you want to add categories default in the Custom Post, that is, without registering a taxonomy in a programmatic way, you can provide this information when registering the Custom Post. Remember which category is basically a taxonomy. So, at the end of the day, the result will be the same. The registration code would be something like

register_post_type('produto',
    array(
        'labels' => array(
            //todos os seus labels
            ),

        'public' => true,
        'show_ui' => true,
        'supports' => array( 'title', 'editor', 'thumbnail' ),
        // ...
        //todo o resto dos seus parâmetros de criação
        // ...
        'taxonomies' => array('category'), // <=== habilita o uso de categorias por default

     )
);
  • 1

    Thank you so much for your reply. It worked perfectly!

  • @Diegooli arrange

Browser other questions tagged

You are not signed in. Login or sign up in order to post.