Rob
Rob

Reputation: 6370

Only show sub categories for a post

I have a custom post that I want to show all the categories it's a part of. There's two parts to this, at the top of the page I'm only showing the top level categories that it's a part of, this is how I did it:

<?php $term_list = wp_get_post_terms($post->ID, 'project-categories', array('fields' => 'all', 'parent' => 0));
foreach($term_list as $term) { ?>

    <div class="type-block">
        <span class="type-initial"><?php echo the_field('category_initials', 'project-categories_' . $term->term_id); ?></span>
        <span class="type-name type-name-<?php echo $term->term_id; ?>"><?php echo $term->name; ?></span>
    </div>                              

<?php } ?>

Towards the bottom of the page I want to only show the sub categories that it's a part of - these sub categories could be part of several top level categories. How can I display them? This was my attempt:

<?php $term_list = wp_get_post_terms($post->ID, 'project-categories', array('fields' => 'all', 'parent' => array(7, 10, 8, 9, 11)));
foreach($term_list as $term) { ?>

    <div class="type-block type-block-black">
        <span class="type-initial"><?php echo the_field('category_initials', 'project-categories_' . $term->term_id); ?></span>
        <span class="type-name type-name-<?php echo $term->term_id; ?>"><?php echo $term->name; ?></span>
    </div>                              

<?php } ?>

At the moment it's only showing the last sub category, how can I show multiple categories?

Upvotes: 2

Views: 338

Answers (2)

KEYUR THUMMAR
KEYUR THUMMAR

Reputation: 16

<?php
$servername="localhost";
$username="root";
$password="";
$dbname="demon";
//CREATE CONNECTION
$conn=new mysqli($servername,$username,$password,$dbname);
//CHECK CONNECTION
if ($conn->connect_error) 
{
    die("CONNECTION FAILED:".$conn->connect_error);
}
$sql="select * from subcategory";
$result=$conn->query($sql);
while($row=$row=$result->fetch_assoc())
{
    echo "<b><hr>NEW RECORDS<hr/></b>";
    echo $row["SUBCATEGORY_ID"] ."<br/>"."</hr>";
    echo $row["CATEGORY_ID"] ."<br/>"."</hr>";
    echo $row["SUBCATEGORY_NAME"] ."<br/>"."</hr>";
    //print_r($row);
    }
$conn->close();
?>

Upvotes: 0

Vidhi
Vidhi

Reputation: 2034

Try this code

<?php 
    $term_list = wp_get_post_terms($post->ID, 'project-categories', array('fields' => 'all'));
    $term_list = wp_list_filter($term_list, array('parent'=>'0'),'NOT');
    foreach($term_list as $term) { ?>

        <div class="type-block type-block-black">
            <span class="type-initial"><?php echo the_field('category_initials', 'project-categories_' . $term->term_id); ?></span>
            <span class="type-name type-name-<?php echo $term->term_id; ?>"><?php echo $term->name; ?></span>
        </div>                              

<?php } ?>

Upvotes: 2

Related Questions