Home > OS >  Showing selected categories in a single of a custom post type (Wordpress)
Showing selected categories in a single of a custom post type (Wordpress)

Time:12-11

I created a custom post type called members:

// Custom post types

function members_post_type()
{
    $args = array(
        'labels' => array(
            'name' => 'Members',
            'singular_name' => 'Member',
            'all_items' => 'All members'
        ),
        // 'hierarchical' => true,
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor' , 'thumbnail'),
        'menu_icon' => 'dashicons-groups'
    );
    register_post_type('members', $args);
}

add_action('init', 'members_post_type');

function members_taxonomys()
{
    $args = array(
        'public' => true,
        'hierarchical' => true
    );
    register_taxonomy('Categories', array('members'), $args);
}

add_action('init', 'members_taxonomys');
And in single-members.php I made this code to call my categories:

<?php if(have_posts()):?>
<?php while(have_posts() ): ?>
    <?php 
        the_category(' ');
    ?>

And for some reason, it didn't work. Feel free to ask more questions or more details.

CodePudding user response:

  1. Hi, first of all you need to change the name of your custom taxonomy and give it a label:
function members_taxonomys()
{
    $args = array(
        'label'                 => 'My categories', // Label
        'public' => true,
        //'show_admin_column'     => true,
        'hierarchical' => true
    );
    // Custom category 
    register_taxonomy('my_categories', array('members'), $args);
}

add_action('init', 'members_taxonomys');

  1. When creating your own post type, you need remove rewrite rules:
function members_post_type()
{
    $args = array(
        'labels' => array(
            'name' => 'Members',
            'singular_name' => 'Member',
            'all_items' => 'All members'
        ),
        // 'hierarchical' => true,
        'public' => true,
        'query_var'           => true,
        'rewrite'             => true,
        'has_archive' => true,
        'supports' => array('title', 'editor' , 'thumbnail'),
        'menu_icon' => 'dashicons-groups'
    );
    register_post_type('members', $args);

    flush_rewrite_rules(false); // Remove rewrite rules 
}
  1. Create a new members post and assign your custom taxonomy to it

  2. Then you need to replace the the_category(); function because it works with the standard category taxonomy, you need to use get_the_terms function

<?php if(have_posts()):?>
<?php while(have_posts() ): the_post(); ?>
    <?php 
       $categories = get_the_terms($post, 'my_categories');
       if(!empty($categories)) {
           ?><ul><?php
                foreach($categories as $cat) {
                    print "<li>$cat->name</li>";
                }
           ?></ul><?php           
       }        
    ?>
<?php endwhile; ?>
<?php endif;?>
  • Related