How to create categories for a Post type in Wordpress?

1

Simple doubts, but I can not find a solution. I created a Post type called "Products" in functions.php, but it does not come with categories natively. What do I put in the functions to allow the user to give a category to a Product? I got 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 Post Product type. How to do to have different categories for each type of Post?

    
asked by anonymous 29.10.2015 / 21:36

1 answer

1

You can achieve your goal by registering a custom taxonomy for your Custom Post as follows (I'll 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 the files of your plugin or your functions.php . Stay tuned for the way you baptize your Custom Posts and Custom Taxonomies. The use of words like category (which must be a reserved word in WP) can be evil.

More about method register_taxonomy() no codex .

If you want to add default categories to Custom Post , ie without registering a taxonomy programmatically, you can provide this information when registering the < in> Custom Post . It is worth remembering that category is, basically, a taxonomy. So, in the end, the result will be the same. The registration code would look 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

     )
);
    
30.10.2015 / 02:48