admin管理员组

文章数量:1420086

I have this code

        while( $animes->have_posts() ) {
        $animes->the_post();
        $i++;
        $animeID[$i] = $post->ID;

        $args = array(
            'orderby' => 'meta_value_num',
            'order' => 'DESC',
            'fields' => 'all',
            'meta_query' => [['key' => 'episode_number','type' => 'NUMERIC',]]
        );

        $episodes[$i] = wp_get_post_terms(intval( $animeID[$i] ), 'episodes', $args );
        }
    }

I want to merge all $episodes[$i] in one array is it possible?

I have this code

        while( $animes->have_posts() ) {
        $animes->the_post();
        $i++;
        $animeID[$i] = $post->ID;

        $args = array(
            'orderby' => 'meta_value_num',
            'order' => 'DESC',
            'fields' => 'all',
            'meta_query' => [['key' => 'episode_number','type' => 'NUMERIC',]]
        );

        $episodes[$i] = wp_get_post_terms(intval( $animeID[$i] ), 'episodes', $args );
        }
    }

I want to merge all $episodes[$i] in one array is it possible?

Share Improve this question asked Jul 11, 2019 at 18:45 Gamal MohamedGamal Mohamed 1
Add a comment  | 

1 Answer 1

Reset to default 0

Rather than placing the result of wp_get_post_terms() into $episodes[$i], you can just merge it into the $episodes array using array_merge(), like this:

$episodes = []; // Initialise as an empty array first.

while( $animes->have_posts() ) {
    $animes->the_post();
    $animeID[] = get_the_ID();

    $args = array(
        'orderby'    => 'meta_value_num',
        'order'      => 'DESC',
        'fields'     => 'all',
        'meta_query' => [
            [
                'key'  => 'episode_number',
                'type' => 'NUMERIC',
            ],
        ],
    );

    $episodes = array_merge( $episodes, wp_get_post_terms( get_the_ID(), 'episodes', $args );
}

I also simplified the code, removing the unnecessary $i variable and using get_the_ID() to get the current post ID.

All that being said, if you have a query of posts, and want to get the terms used by the posts in that query, you can just past a list of post IDs to get_terms() using the object_ids argument:

$anime_ids = wp_list_pluck( $animes->posts, 'ID' );
$episodes  = get_terms(
    'object_ids' => $anime_ids,
    'meta_key'   => 'episode_number',
    'orderby'    => 'meta_value_num',
    'order'      => 'DESC',
);

本文标签: phpMerge wpgetpostterms