0

I queried posts from an array of IDs:

$args = array(
    'post_type' => 'post',
    'post__in' => $ids,
    'orderby' => 'id',
    'order' => 'DESC'
);

Now I want to display a form with checkboxes for the categories of these queried posts. For example if there are two posts from the category "Drama" I dont want the "Comedy"-Category-Checkbox to be displayed.

The problem: As there is no post__in parameter for get_categories, I have no idea, how I can do this.

$catargs = array(
    'post__in' => $ids,
);

$categories = get_categories(  $catargs  ); ?>
1

You need a:

  1. array of post id ( ok )
  2. array of category id ( not yet )
  3. array of category id/name with unique value ( not yet )

using wp_get_posts_categories( $post_id ); returns an array of category id, so you can loop your $ids calling this function to collect all categories id.

with the array of categories id you can set up a brand new one with id/name pair and then with array_unique(); clean up it from duplicated values.

I can't find any other solution, so:

UPDATE

<?php
/*
 *Loop through your $ids and:
 * get all the categories id for your queried posts ( wp_get_post_categories( $id ) )
 * loop through this new array to get single category data ( get_category( $catid ) )
 * set up a new array with term_id/name value pairs ( $categories )
 * clean up your new array from duplicate values ( array_unique( $categories ) )
 */
foreach( $ids as $id ){
$catids = wp_get_post_categories( $id );
  foreach( $catids as $catid ){
    $category = get_category( $catid );
    $categories[$category->term_id] = $category->name; 
  }
}

$filtered_categories = array_unique($categories);

?>

I've tested and now works. Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.