Get Custom Taxonomy Title by Spesific Sub Category via fputcsv

I had all posts under different Sub-Categories (taxonomy is ‘category’ / default WP) within one Category and also under Custom Taxonomy (taxonomy is ‘program’) something like this:

– Parent Category 1
– Parent Category 2 (*only this Category that have Custom Taxonomy)
— Sub-Category A
— Program a
— Program b
— Sub-Category B
— Program a
— Program b
– Parent Category 3

And I want to get the tittle of Custom Taxonomy (‘Program a’, ‘Program b’, etc…) for each posts and then send it via fputcsv function.

For current code as below, I can get the results as expected but it also display the title of Custom Taxonomy (in this case: ‘Program b’) that should have an empty object (from Sub-Category A) below new row too:

Post | Category | Sub-Category | Program
Post Title 1 | Category 2*| Sub-Category B | Program a
Post Title 2 | Category 2*| Sub-Category A | Program b
Post Title 3 | Category 3 | | Program b
Post Title 4 | Category 1 | | Program b

Desired output in csv by using fputcsv is something like this:

Post | Category | Sub-Category | Program
Post Title 1 | Category 2*| Sub-Category B | Program a
Post Title 2 | Category 2*| Sub-Category A | Program b
Post Title 3 | Category 3 | |
Post Title 4 | Category 1 | |

This is the current code:

foreach ($arr_post as $post)
{
$idpost = $post->ID;

$catList = get_the_category();
foreach($catList as $cat)
{
if ($cat->category_parent == 0)
{
$maincatList = $cat->cat_name;
}
}

$subcats = get_the_category($query->$idpost);
foreach($subcats as $subcat)
{
if (!empty($subcats))
{
$subcatList = $subcats[1]->cat_name;
}
}

$progrs = get_the_terms($query->$idpost, ‘program’);
foreach($progrs as $progr)
{
if (!empty($progrs))
{
$progList = $progr->name;
}
}

setup_postdata($post);

fputcsv($file, array_map(“utf8_decode”,
array(
get_the_title(),
$maincatList,
$subcatList,
$progList,
)
));
}

Read more here:: Get Custom Taxonomy Title by Spesific Sub Category via fputcsv

Leave a Reply

Your email address will not be published. Required fields are marked *