Forums

Display only parent category of a custom taxonomy (4 posts)

  1. nathanadams
    Member
    Posted 5 months ago #

    I've set up a custom hierarchal taxonomy called Make & Model, with the make as parent categories, and models as child categories of the makes. For example:

    BMW
    - 318i
    - Isseta
    Daewoo
    - Espero
    - Laganza

    What I'd like to do is to display the parent category on it's own (and then the child category/ies) on their own within the individual post. For example:

    Make: BMW
    Model: Isseta

    Is that at all possible?

    Thanks

  2. nathanadams
    Member
    Posted 5 months ago #

    No one has attempted something like this before, or knows how it could be done? Any help will be appreciated.

  3. aljuk
    Member
    Posted 4 months ago #

    This is how I'm doing it:

    1. The taxonomy slugs:

    parent taxonomy slug: bmw
    child taxonomy slug: bmw-isseta

    2. The set up:

    <?php if(get_the_terms($post->ID,'model')){
    $makemodel = wp_get_object_terms($post->ID, 'model', array('orderby' => 'slug')); } ?>

    3. Outputting the make:

    <?php if(!empty($makemodel) && get_term_link($makemodel[0])){ ?>
    <a href="<?php echo get_term_link($makemodel[0]); ?>"><?php echo $makemodel[0]->name; ?></a>
    <?php } ?>

    4. Outputting the model:

    <?php if(!empty($makemodel) && get_term_link($makemodel[1])){ ?>
    <a href="<?php echo get_term_link($makemodel[1]); ?>"><?php echo $makemodel[1]->name; ?></a>
    <?php } ?>
  4. nathanadams
    Member
    Posted 4 months ago #

    Thanks aljuk, that looks like a nice simple way of doing it.

    I ended up using a different method which checks for if the the category has a parent or not:

    For make:
    <?php $make =""; $i = 1; foreach((get_the_terms( $post->ID, 'make' )) as $makecat) {if ($makecat->parent == 0) {$make .= $makecat->name; if($i == 1) break;}} echo $make; ?>

    For model:
    <?php $model =""; $i = 1; foreach((get_the_terms( $post->ID, 'make' )) as $modelcat) {if ($modelcat->parent |= 0) {$model .= $modelcat->name; if($i == 1) break;}} echo $model ?>

Reply

You must log in to post.

About this Topic