1

I try to display a list of custom posts grouped by categories using a solution from here (the 1st option/example). I adapted the code only a little to my needs, but it freezes (get a white display if it isn't commented) my installation/blog, because of this line (as it seems to me): $term_ids = array_map(function($t) { return $t->term_id, }, $terms);. I found that by commenting parts of the code. What is wrong with it?

My full code:

function yesterday_events2() {

    $terms = get_terms( 'event-categories' );

    $term_ids = array_map( function( $t ) { return $t->term_id }, $terms );

    $posts = get_posts(
        array(
            'nopaging'  => true,
            'tax_query' => array(
                array(
                    'taxonomy' => 'event-categories',
                    'field'    => 'id',
                    'terms'    => $term_ids,
            ) ),
    ) );

    foreach( $terms as $t ) {
        $posts_in_term = array_filter( $posts, function( $p ) use ( $t ) {
            // has_term likely triggers a DB hit...
            return has_term( $t->term_id, 'event-categories', $p );
        } );

        // do stuff with $posts_in_term 
    }

}

1 Answer 1

2

You should write it as the following:

$term_ids = array_map( function( $t ) { return $t->term_id ; }, $terms );

Also in the code, you have the get_terms where you directly write the taxonomy name. This has been deprecated in favor of the following :

$terms = get_terms( array(
    'taxonomy' => 'event-categories',
    'hide_empty' => false,
) );

Since 4.5.0, taxonomies should be passed via the ‘taxonomy’ argument in the $args array:

Second Question

About why you have an empty posts:

You are searching by default in the posts with post_type=post.

You should search for your custom post_type like this:

$posts = get_posts(
    array(
        'post_type' => 'custom_post_type',
        'nopaging'  => true,
        'tax_query' => array(
            array(
                'taxonomy' => 'event-categories',
                'terms'    => $term_ids ,
        ) ),
) );

I removed the 'field' => 'id' Because by default it gets the term_id and the accepted values are :

  • 'term_id'
  • 'name'
  • 'slug'
  • 'term_taxonomy_id'
2
  • Thank you very much! Can you, please, also evaluate the $posts = ... part? When I test it with count( $posts ) I get zero posts :(.
    – Yuri
    Commented Dec 4, 2017 at 19:57
  • 1
    I have updated my answer. :) Commented Dec 4, 2017 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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